Simple haskell splitlist

后端 未结 2 1025
闹比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: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)
    

提交回复
热议问题