[Haskell-beginners] Partition a list recursively

Francesco Ariis fa-ml at ariis.it
Tue Nov 3 11:46:29 UTC 2015


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.

> 
> 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)


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

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



More information about the Beginners mailing list