Reputation: 2449
How can I make a function that groups element of a list into lists of predefined length without using explicit recursion.
For example, for 2:
[1, 2, 3, 4, 5, 6, 7, 8]
[[1, 2], [3, 4], [5, 6], [7, 8]]
Thank you!
Upvotes: 1
Views: 200
Reputation: 47402
The following would work (though you may consider it cheating to use groupBy
from Data.List)
import Data.Function (on)
import Data.List (groupBy)
group :: Int -> [a] -> [[a]]
group n = map (map snd)
. groupBy ((==) `on` fst)
. zip (enumFrom 1 >>= replicate n)
Upvotes: 2
Reputation: 32319
This is a one-liner if you set your wrap at 100 characters :). I'm guessing you are looking for something that uses a fold.
group :: Int -> [a] -> [[a]]
group n = uncurry (:) . foldr (\x (l,r) -> if length l == n then ([x],l:r)
else (x:l,r))
([],[])
Upvotes: 1