Does F# has function to "flat" a map to list, like scala?

2k views Asked by At

I wonder if F# has a function called "flat" to flatter a map to be a list, like from

{(1,"hello"),(2, "world")}

to

{1, "hello", 2, "world"}.

Scala has this function, does F# has?

In other words, could a F# list contain elements with different types? Thanks.

1

There are 1 answers

1
Søren Debois On BEST ANSWER

F# doesn't have a type of "lists with differently typed elements", but you can do the following.

First, you can convert between maps and lists of pairs:

> let xs = [(1, "foo"); (2, "bar")] ;;
val xs : (int * string) list = [(1, "foo"); (2, "bar")]

> let m = Map.ofSeq xs;;
val m : Map<int,string> = map [(1, "foo"); (2, "bar")]

> let ys = m |> Map.toSeq |> List.ofSeq;;
val ys : (int * string) list = [(1, "foo"); (2, "bar")]

Then you can cast the components in each pair to object, then flatten that into a list of objects:

> 
- let zs = 
-   ys
-   |> Seq.collect (fun (key, value) -> [(key :> obj); (value :> obj)])
-   |> List.ofSeq;;

val zs : obj list = [1; "foo"; 2; "bar"]

I don't know how helpful this is in practice, though.