Proposal: Add these two handy functions to Data.List

Henning Thielemann lemming at henning-thielemann.de
Mon Jul 5 06:36:06 EDT 2010


On Thu, 1 Jul 2010, Cale Gibbard wrote:

> When working with the list monad, I often find myself in need of one
> of the two following functions:
>
> -- | Produce a list of all ways of selecting an element from a list,
> each along with the remaining elements in the list.
> -- e.g. select [1,2,3,4] == [(1,[2,3,4]),(2,[1,3,4]),(3,[1,2,4]),(4,[1,2,3])]
> -- This is useful for selection without replacement in the list monad
> or list comprehensions.
> select :: [a] -> [(a,[a])]
> select [] = []
> select (x:xs) = (x,xs) : [(y,x:ys) | (y,ys) <- select xs]
>
> -- | Produce a list of all ways of separating a list into an initial
> segment, a single element, and a final segment.
> -- e.g. separate [1,2,3,4] ==
> [([],1,[2,3,4]),([1],2,[3,4]),([1,2],3,[4]),([1,2,3],4,[])]
> separate :: [a] -> [([a],a,[a])]
> separate [] = []
> separate (x:xs) = ([],x,xs) : [(x:us,v,vs) | (us,v,vs) <- separate xs]

I also needed these functions frequently and thus I implemented them in 
utility-ht:

http://hackage.haskell.org/packages/archive/utility-ht/0.0.5.1/doc/html/Data-List-HT.html#v%3AremoveEach
http://hackage.haskell.org/packages/archive/utility-ht/0.0.5.1/doc/html/Data-List-HT.html#v%3AsplitEverywhere


More information about the Libraries mailing list