In search of: [a->b] -> a -> [b]

Derek Elkins ddarius@hotpop.com
Tue, 17 Jun 2003 20:15:15 -0400


On Tue, 17 Jun 2003 21:01:57 +0100
Graham Klyne <gk@ninebynine.org> wrote:

> I'm convinced I've seen a function like this somewhere:
>    [a->b] -> a -> [b]
> but cannot remember where.  Or maybe:
>    Monad m => m (a->b) -> a -> m b
> ?
> 
> I could roll my own (*), but I'm trying not to duplicate standard
> library functions is I can help it.  Any pointers?

The closest function I see is ap :: Monad m => m (a -> b) -> m a -> m b
(so you could write your function as f fs a = ap fs (return a) not that
I would recommend it).  Also you may want to check out the Haskell
reference at zvon.org, it's indexed by type as well.

 
> #g
> --
> 
> (*)
> 
>      flist :: [a->b] -> a -> [b]
>      flist fs a = map (flip ($) a) fs
or much nicer (IMO) 
  flist fs a = map ($ a) fs 
or breakin' out the point-free style, 
  flist = flip (map . flip ($)) -- okay, so I wouldn't recommend this

the generalized solution being simply,
f mf x = do
    f <- mf
    return (f x)

ap is almost certainly liftM2 ($) or equivalently,
ap mf mx = do
    f <- mf
    x <- mx
    return (f x)
 
>      flist [(1*),(2*),(3*)] 5 -- = [5,10,15]