Splitting a list into list of lists based on predicate

前端 未结 5 2129
感动是毒
感动是毒 2021-01-21 03:28

(I am aware of this question, but it relates to sequences, which is not my problem here)

Given this input (for example):

let testlist = 
    [  
       \         


        
5条回答
  •  半阙折子戏
    2021-01-21 03:58

    Another version of shunt:

    let shunt pred lst =
        let rec tWhile pred lst = 
            match lst with
            | []                    -> [], []
            | hd :: tl when pred hd -> let taken, rest = tWhile pred tl
                                       (hd :: taken), rest
            | lst                   -> [], lst
        let rec collect = function
            | []  -> []
            | lst -> let taken, rest = tWhile pred lst
                     taken :: (collect (snd (tWhile (fun x -> not (pred x)) rest)))
        collect lst
    

    This one avoids List.rev but it's not tail recursive - so only suitable for small lists.

提交回复
热议问题