Home > Net >  Splitting list into odd and even (Haskell)
Splitting list into odd and even (Haskell)

Time:10-03

I need to create a function that will take a list of integers and split them into 2 lists, one with odd numbered and the other even

split :: [a] -> ([a], [a])
split = undefined

Above is the function baseline, below is current attempt I have

 split :: [a] -> ([a], [a])
 split [] = ([],[])
 split (x:xs) | x mod 2 == 0 = ([],[x:split xs])
         | x mod 2 /= 0 = ([x:split xs],[])
         | otherwise = ([],[])

CodePudding user response:

explicit recursion:

split :: Integral a => [a] -> ([a], [a])
split []        = ([], [])
split (x:xs)
  | even x      = (x:ys, zs)
  | otherwise   = (ys, x:zs)
  where
    (ys, zs) = split xs

implicit recursion:

splitf :: Integral a => [a] -> ([a], [a])
splitf xs = foldr (\x (ys, zs) -> if even x then (x:ys, zs) else (ys, x:zs)) 
                  ([], []) xs

which you can eta reduce to point-free style:

splitf2 :: Integral a => [a] -> ([a], [a])
splitf2 = foldr (\x (ys, zs) -> if even x then (x:ys, zs) else (ys, x:zs)) 
                ([], [])

I think the code is self explanatory. If there is anything I need to further explain, please let me know.

  • Related