Search code examples
castingf#tuplesboxingseq

Seq.cast tuple values from obj to string


What is the nice and working way of doing a cast like this?

seq { yield (box "key", box "val") }
|> Seq.cast<string*string>

Since this looks extremely ugly:

seq { yield (box "key", box "val") }
|> Seq.map (fun (k,v) -> k.ToString(), v.ToString())

As well as this:

seq { yield (box "key", box "val") }
|> Seq.map (fun (k,v) -> unbox<string>(k), unbox<string>(v)) 

Is there a way to "unbox" a tuple into another tuple?


Solution

  • You could write it slightly nicer as:

    seq { yield (box "key", box "val") }
    |> Seq.map (fun (k, v) -> string k, string v)
    

    Imagine, however, that you have a Tuple2 module:

    module Tuple2 =
        // ... other functions ...
    
        let mapBoth f g (x, y) = f x, g y
    
        // ... other functions ...
    

    With such a mapBoth function, you could write your cast as:

    seq { yield (box "key", box "val") } |> Seq.map (Tuple2.mapBoth string string)
    

    There's no Tuple2 module in FSharp.Core, but I often define one in my projects, containing various handy one-liners like the one above.