Home > OS >  How should I partition a list?(Without using libraries)
How should I partition a list?(Without using libraries)

Time:05-28

How should I partition a list?(Without using libraries)

For example :

input

[0,1,1,1,1,0,0,0,1]

output

[[0,1,1],[1,1,0],[0,0,1]]

CodePudding user response:

You can recursively each time split the list after n elements, and then yield the first item, and recurse on the remaining items, so:

partition :: Int -> [a] -> [[a]]
partition n = go
    where go [] = []
          go xs = ys : go yss
              where (ys, yss) = splitAt n xs

For example:

ghci> partition 3 [0,1,1,1,1,0,0,0,1]
[[0,1,1],[1,1,0],[0,0,1]]

CodePudding user response:

I've managed to do it by using take and drop in a list comprehension.(I was having trouble becaue i wrote take first and drop second, giving me incorrect partitions)

Here's what worked for me

[ drop ((size)*x) (take ((size)*(x 1)) (list)) | x<-[0..size]]

  • Related