A simple haskell partition list

I have the following function that takes a list and returns two subnets divided by a given element n. However, I only need to split it in half, with lists with odd lengths having a larger first sublist

splitlist :: [a] -> Int -> ([a],[a])
splitlist [] = ([],[])
splitlist l@(x : xs) n | n > 0     = (x : ys, zs)
               | otherwise = (l, [])
    where (ys,zs) = splitlist xs (n - 1)

I know that I need to change the signature to [a] → ([a], [a]), but where in the code should I put something like length (xs) so that I don't break the recursion? Thank.

+3
source share
2 answers

You can do this with 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 use the splitAt function:

splitlist list = splitAt ((length (list) + 1) `div` 2) list
+6
source

In a real program, you should probably use

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

(i.e. something in accordance with the answer to the dream).

, :

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)
+7

All Articles