I want to convert [1,2,3,4]
to [[1 2] [2 3] [3 4]]
or [(1 2) (2 3) (3 4)]
. In clojure I have (partition 2 1 [1,2,3,4])
. H
Just to throw another answer out there using a different approach:
For n=2 you want to simply zip
the list with its tail. For n=3 you want to zip the list with its tail and with the tail of its tail. This pattern continues further, so all we have to do is generalise it:
partition n = sequence . take n . iterate tail
But this only works for an offset of 1. To generalise the offsets we just have to look at the genrated list. It will always have the form:
[[1..something],[2..something+1],..]
So all left to do is select every offset
th element and we should be fine. I shamelessy stole this version from @ertes from this question:
everyNth :: Int -> [a] -> [a]
everyNth n = map head . takeWhile (not . null) . iterate (drop n)
The entire function now becomes:
partition size offset = everyNth offset . sequence . take size . iterate tail