Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subdividing a list in haskell

Tags:

haskell

How can I group a list into smaller lists of equal length (except last sublist) in haskell?

E.g.

sublist 3 [1,2,3,4,5,6,7,8] -> [[1,2,3],[4,5,6],[7,8]]
sublist 2 [4,1,6,1,7,3,5,3] -> [[4,1],[6,1],[7,3],[5,3]]
like image 652
aufziehvogel Avatar asked Dec 30 '11 15:12

aufziehvogel


People also ask

How do I split a list in Erlang?

You can use lists:split/2 for this: divide(L, N) -> divide(L, N, []). divide([], _, Acc) -> lists:reverse(Acc); divide(L, N, Acc) when length(L) < N -> lists:reverse([L|Acc]); divide(L, N, Acc) -> {H,T} = lists:split(N, L), divide(T, N, [H|Acc]).

What is cons operator in Haskell?

The : operator is known as the "cons" operator and is used to prepend a head element to a list. So [] is a list and x:[] is prepending x to the empty list making a the list [x] . If you then cons y:[x] you end up with the list [y, x] which is the same as y:x:[] .


3 Answers

Try:

import Data.List.Split
> splitEvery 2 [4,1,6,1,7,3,5,3]
[[4,1],[6,1],[7,3],[5,3]]
like image 195
Chris Avatar answered Oct 16 '22 09:10

Chris


If you want to stick to prelude, you can pull this off using splitAt.

splitEvery _ [] = []
splitEvery n list = first : (splitEvery n rest)
  where
    (first,rest) = splitAt n list
like image 28
redxaxder Avatar answered Oct 16 '22 07:10

redxaxder


The Data.List.Split module has a chunksOf function for this:

Prelude> import Data.List.Split

Prelude Data.List.Split> chunksOf 3 [1,2,3,4,5,6,7,8,9,10]
[[1,2,3],[4,5,6],[7,8,9],[10]]
Prelude Data.List.Split> chunksOf 3 []
[]

It seemed to be installed by default on my machine, but you might need to get it with cabal.

like image 31
Desty Avatar answered Oct 16 '22 09:10

Desty