Linked list partition function and reversed results

前端 未结 5 729
耶瑟儿~
耶瑟儿~ 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 00:51

    You can rewrite the function like this:

    let partitionWhile c l =
      let rec aux xs =
        match xs with
          | [] -> ([], [])
          | h :: t ->
              if c h then
                let (good, bad) = aux t in
                  (h :: good, bad)
              else
                ([], h :: t)
      aux l
    

    Yes, as Brian has noted it is no longer tail recursive, but it answers the question as stated. Incidentally, span in Haskell is implemented exactly the same way in Hugs:

    span p []       = ([],[])
    span p xs@(x:xs')
        | p x       = (x:ys, zs)
        | otherwise = ([],xs)
        where (ys,zs) = span p xs'
    

    A good reason for preferring this version in Haskell is laziness: In the first version all the good elements are visited before the list is reversed. In the second version the first good element can be returned immediately.

提交回复
热议问题