Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to partition a list in Haskell?

Tags:

haskell

I want to take a list (or a string) and split it into sub-lists of N elements. How do I do it in Haskell?

Example:

mysteryFunction 2 "abcdefgh"
["ab", "cd", "ef", "gh"]
like image 883
Alex B Avatar asked Nov 27 '22 03:11

Alex B


2 Answers

cabal update
cabal install split

And then use chunksOf from Data.List.Split

like image 172
is7s Avatar answered Dec 05 '22 04:12

is7s


Here's one option:

partition :: Int -> [a] -> [[a]]
partition _ [] = []
partition n xs = (take n xs) : (partition n (drop n xs))

And here's a tail recursive version of that function:

partition :: Int -> [a] -> [[a]]
partition n xs = partition' n xs []
  where
    partition' _ [] acc = reverse acc
    partition' n xs acc = partition' n (drop n xs) ((take n xs) : acc)
like image 20
Paul Manta Avatar answered Dec 05 '22 04:12

Paul Manta