Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 273
derwasp Avatar asked Jul 27 '16 13:07

derwasp


1 Answers

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.

like image 51
Mark Seemann Avatar answered Nov 10 '22 10:11

Mark Seemann