简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM