R – How to use the F# Reflection library

%freflection

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)

Best Answer

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)