0

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 ?

N.T.C
  • 658
  • 2
  • 9
  • 20

3 Answers3

6

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 ]
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • the original list is a list of tuple of 2 items. Should I have a bracket around and b, in other words [ for (a, b) in original do yield a yield b ] ? (I've tested the code, both ways gave the same results) Which one is correct and why ?> – N.T.C Nov 16 '14 at 07:51
  • If they both work and they both produce the same results, then they're both correct. Parens are only mandatory in F# when the lack of them leads to ambiguity and compiler errors. – Joel Mueller Nov 26 '14 at 20:44
5

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.

Gus
  • 25,839
  • 2
  • 51
  • 76
2
[(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.

sgtz
  • 8,849
  • 9
  • 51
  • 91