Linked list partition function and reversed results

前端 未结 5 730
耶瑟儿~
耶瑟儿~ 2020-12-02 00:26

I wrote this F# function to partition a list up to a certain point and no further -- much like a cross between takeWhile and partition.

<         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 01:02

    I usually prefer Sequences over List as they are lazy and you got List.toSeq and Seq.toList functions to convert between them. Below is the implementation of your partitionWhile function using sequences.

    let partitionWhile (c:'a -> bool) (l:'a list) = 
        let fromEnum (e:'a IEnumerator) = 
            seq { while e.MoveNext() do yield e.Current}
        use e = (l |> List.toSeq).GetEnumerator()
        (e |> fromEnum |> Seq.takeWhile c |> Seq.toList)
        ,(e |> fromEnum |> Seq.toList)
    

提交回复
热议问题