Reputation: 335
Hi I need to split list by an argument in Haskell. I found function like this
group :: Int -> [a] -> [[a]]
group _ [] = []
group n l
| n > 0 = (take n l) : (group n (drop n l))
| otherwise = error "Negative n"
But what if lists that I want to divide are contained by another list?
For example
group 3 [[1,2,3,4,5,6],[2,4,6,8,10,12]]
should return
[[[1,2,3],[4,5,6]],[[2,4,6],[8,10,12]]]
Is there any way to do that ?
Upvotes: 1
Views: 399
Reputation: 3716
You want this:
group n = map (toList . splitAt n)
where
toList (x,y) = [x,y]
UPDATE Given that the specification involves repeated taking and dropping here's how I would do it:
import Data.List (unfoldr)
import Data.Maybe (listToMaybe)
group :: Int -> [[a]] -> [[[a]]]
group n = map (unfoldr split)
where
split = (\s -> listToMaybe (fst s) >> Just s) . splitAt n
You'll notice that inside here is also the definition of what you have implemented as group
. It is unfoldr split
.
Upvotes: 0
Reputation: 14174
Just do map
over the elements (lists) of that list:
grouplists :: [[a]] -> Int -> [[[a]]]
grouplists input n = map (group n) input
Upvotes: 3