Simple haskell splitlist

后端 未结 2 1009
闹比i
闹比i 2020-12-21 03:25

I have the following function which takes a list and returns two sublists split at a given element n. However, I only need to split it in half, with odd length lists having

相关标签:
2条回答
  • 2020-12-21 03:26

    You can do it using take and drop:

    splitlist :: [a] -> ([a],[a])
    splitlist [] = ([],[])
    splitlist l  = let half = (length(l) +1)`div` 2
                   in (take half l, drop half l)
    

    or you can take advantage of the function splitAt:

    splitlist list = splitAt ((length (list) + 1) `div` 2) list
    
    0 讨论(0)
  • 2020-12-21 03:40

    In a real program you should probably use

    splitlist :: [a] -> ([a], [a])
    splitlist xs = splitAt ((length xs + 1) `div` 2) xs
    

    (i.e. something along the lines of dreamcrash's answer.)

    But if, for learning purposes, you're looking for an explicitly recursive solution, study this:

    splitlist :: [a] -> ([a], [a])
    splitlist xs = f xs xs where
        f (y : ys) (_ : _ : zs) =
            let (as, bs) = f ys zs
            in (y : as, bs)
        f (y : ys) (_ : []) = (y : [], ys)
        f ys [] = ([], ys)
    
    0 讨论(0)
提交回复
热议问题