tags:

views:

382

answers:

3

I am trying to follow this example (from p137 of Rob Pickering's "Foundations of F#" book) but I can't get it to work with the latest F# CTP.

I appear to be missing the definition of 'Value' on the 3rd line where it does

Value.GetInfo(x)

This generates :

error FS0039: The namespace or module 'Value' is not defined.

Can anyone tell me where this is coming from or what the new syntax is if this is now done differently? (be gentle - this is my first play with F#)

Here's the example I am working from:-

#light
open Microsoft.FSharp.Reflection
let printTupleValues x =
    match Value.GetInfo(x) with
    | TupleValue vals ->
    print_string "("
    vals
    |> List.iteri
        (fun i v ->
            if i <> List.length vals - 1 then
                Printf.printf " %s, " (any_to_string v)
            else
                print_any v)
    print_string " )"
    | _ -> print_string "not a tuple"

printTupleValues ("hello world", 1)
A: 

I don't know whether your function has been renamed or removed in the current F# versions. You should take a look at FSharp.Reflection in your IDE's object explorer to check that and maybe read this page.

Dario
+4  A: 

The F# reflection library was rewritten for either Beta 1 or the CTP. Here is your code slightly changed to use the new library, and to avoid using the F# PlusPack (print_string is for OCaml compatibility).

open Microsoft.FSharp.Reflection

let printTupleValues x =
    if FSharpType.IsTuple( x.GetType() ) then
        let s =
            FSharpValue.GetTupleFields( x )
            |> Array.map (fun a -> a.ToString())
            |> Array.reduce (fun a b -> sprintf "%s, %s" a b)
        printfn "(%s)" s
    else 
        printfn "not a tuple"

printTupleValues ("hello world", 1)
James Hugard
+2  A: 

Or, if you prefer using match to decompose the tuple, then try this using an active pattern. Advantage is you can add support for additional types pretty easily.

open Microsoft.FSharp.Reflection

let (|ParseTuple|_|) = function
    | o when FSharpType.IsTuple( o.GetType() ) ->
        Some( FSharpValue.GetTupleFields(o) )
    | _ -> None

let printTupleValues = function
    | ParseTuple vals ->
        let s =
            vals
            |> Array.map (fun a -> a.ToString())
            |> Array.reduce (fun a b -> sprintf "%s, %s" a b)
        printfn "(%s)" s
    | _ ->
        printf "not a tuple"

printTupleValues ("hello world", 1)
James Hugard