[Haskell-beginners] Partition a list recursively

Alexandre Delanoë alexandre+haskell at delanoe.org
Tue Nov 3 13:29:07 UTC 2015


2015/11/03 12:46, Francesco Ariis:
> On Tue, Nov 03, 2015 at 11:12:31AM +0100, Alexandre Delanoë wrote:
> > Hello,
> > I am looking for such function:
> > 
> > function :: Ord a => [a] -> [a] -> [[a]]
> > function [1,3,6] [0..6] == [[0,1],[2,3],[4,5,6]]
> > 
> > Question: does it exist already ?
> 
> ``Data.List.Split`` (from package ``split``) may have what you are
> looking for.

Thanks. I had a look on it but I did not find what I need (maybe I am
wrong). In fact, "span" was exactly the tool indeed (see below).

> > 
> > Let:
> > 
> > partIt :: Ord a => a -> [a] -> [[a]]
> > partIt m xs = [takeWhile (<= m) xs, dropWhile (<= m) xs]
> > example:
> > partIt 1 [0..5] == [[0,1],[2,3,4,5]]
> > 
> > Question: How to define recursively partIt
> > 1) with a list as parameter ?
> > 2) recursively on the second part of the list ?
> 
> With pattern matching:
> 
>     partIt :: Ord a => a -> [a] -> [[a]]
>     partIt []     xs = xs
>     partIt (m:ms) xs = let (a, b) = span (<= m) xs in (a : partIt ms b)

Thanks! Yes, exactly. With some minor corrections:

partIt :: Ord a => [a] -> [a] -> [[a]]
partIt []     xs = [xs]
partIt (m:ms) xs = let (a, b) = span (<= m) xs in (a : partIt ms b)


>     λ> partIt [1,3,6] [0..6]
>     [[0,1],[2,3],[4,5,6],[]] -- expected: splits on 6 too

ok

> 
> Learn You a Haskell has  nice section on pattern matching.
> Did this answer the question?

Yes, now it is time to practice and I discover (each time) how pattern
matching is powerful.

Thanks again,

-- 
	Alexandre Delanoë


More information about the Beginners mailing list