[Haskell-beginners] how to split a list
Francesco Ariis
fa-ml at ariis.it
Mon Mar 26 18:18:29 UTC 2018
On Mon, Mar 26, 2018 at 08:11:44PM +0200, Francesco Ariis wrote:
> There's the usual zip trick
>
> λ> l = [1,2, 3, 4, 6, 7, 9, 10]
> λ> zipWith (-) l [1..]
> [0,0,0,0,1,1,2,2]
> λ> zip l it
> [(1,0),(2,0),(3,0),(4,0),(6,1),(7,1),(9,2),(10,2)]
To be more explicit:
λ> :m +Data.List (groupBy)
λ> :m +Data.Function (on)
λ> l = [1,2, 3, 4, 6, 7, 9, 10]
λ> map (map snd) $ groupBy ((==) `on` snd) $ zip l (zipWith (-) l [1..])
[[0,0,0,0],[1,1],[2,2]]
Maybe with some lens or with a foldr you can end up with something shorter
than this (69 characters).
More information about the Beginners
mailing list