Merge two lists

后端 未结 6 1875
暖寄归人
暖寄归人 2020-12-10 14:01

I am looking to merge 2 lists in F# in a purely functional way. I am having a hard time understanding the syntax.

Let say I have a tuple ([5;3;8],[2;9;4])

6条回答
  •  萌比男神i
    2020-12-10 14:41

    Since F# 4.5 (I think), assuming you want to continue yielding elements from the longer sequence when the shorter is exhausted, you can just do:

    let interleave = Seq.transpose >> Seq.concat >> Seq.toList
    
    > interleave [ [5;3;8]; [2;9;4] ];;
    val it : int list = [5; 2; 3; 9; 8; 4]
    
    > interleave [ [1;2;3]; [4;5]; [6;7;8;9] ];; // also works for any number of lists
    val it : int list = [1; 4; 6; 2; 5; 7; 3; 8; 9]
    

    (Note List.transpose throws if the sequences are of differing length but Seq.transpose does not, so you need to use the latter.)

提交回复
热议问题