简体   繁体   中英

How to convert (int* int) list to (int: list) in F#

I have a sequence pairwise like: Original = [(0,0); (1,2); (3,4)] I would like to convert this seq of (int *int) to a seq of int Final= [0,0,1,2,3,4] Can anyone please suggest me the way to do this ?

Another option is to use sequence expressions - I quite like this option, but it is a matter of personal preferences:

[ for a, b in original do
    yield a
    yield b ]

Use List.collect

[(0,0); (1,2); (3,4)] |> List.collect (fun (x,y) -> [x; y])

In your question you say you want a List at the beginning but at the end you say Sequence, anyway for sequences collect is also available.

For more information collect is the monadic function bind or the operator >>= in some languages (SelectMany in C#) which for lists/sequences is equivalent to a map followed by a concat.

[(0,0); (1,2); (3,4)] |> List.map(fun (x,y)->[x; y]) |> List.concat

ie. map tuple sequence to a list of lists, and then join the lists together

or

[(0,0); (1,2); (3,4)] |> Seq.map(fun (x,y)->seq { yield x; yield y}) |> Seq.concat |> Seq.toList

I came up with the longer Seq version first, because the Seq module traditionally had more operators to work with. However, come F# 4, Seq, List, and Array types will have full operator coverage.

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