List functions - "Under" operations
Ross Paterson
ross at soi.city.ac.uk
Fri Jan 16 12:01:42 EST 2004
On Fri, Jan 16, 2004 at 11:03:21AM +0100, Tomasz Zielonka wrote:
> On Fri, Jan 16, 2004 at 01:43:40AM -0800, Brandon Michael Moore wrote:
> > I think it would often be useful if the list functions with class
> > constraints had versions paramaterized on a function mapping your element
> > type into an instance of the classes, in addition to the "By" forms that
> > take an implementation for the required class method.
> >
> > Almost all of the times I use the "By" functions follow that pattern:
> > e.g.
> > sortFoos :: [Foo] -> [Foo]
> > sortFoos = sortBy (\x y -> compare (f x) (f y))
>
> No need for so many new functions. Just write a function:
>
> composeFGxGy :: (b -> b -> c) -> (a -> b) -> a -> a -> c
> composeFGxGy f g x y = f (g x) (g y)
>
> Then you can:
>
> sortFoos = sortBy (composeFGxGy compare f)
The special case may be useful if f is expensive:
-- sortImage f = sortBy (\x y -> compare (f x) (f y))
sortImage :: Ord b => (a -> b) -> [a] -> [a]
sortImage f xs = map snd (sortBy cmp_fst [(f x, x) | x <- xs])
where cmp_fst (x,_) (y,_) = compare x y
More information about the Libraries
mailing list