Multiple functions applied to a single value

Graham Klyne gk at ninebynine.org
Thu Nov 27 14:56:03 EST 2003


There's a possible programming idiom that I repeatedly find myself thinking 
about as I write my code.  It feels like a kind of dual of fold, except 
that it's not necessarily confined to lists.  I'm wondering if anything 
like this is discussed in the literature, or implemented in the libraries...

Scene-setting:  broadly speaking, fold takes a function and applies it to 
several values, and combines the results in some way.  What I'm thinking of 
is a combinator or suchlike that takes two or more functions, applies them 
(separately) to a single value, then combines the results of those 
combinations.

One function that I have defined and use in my code is called 'flist':

   flist :: [a->b] -> a -> [b]
   flist fs a = map ($ a) fs

(which is similar to Monad.ap, except that the 'a' parameter is not a 
list/monad).  I could imagine combining this with a fold in some cases.

A more generalized form of this that works with arbitrary monads was 
suggested by Derek Elkin:

fmonad :: Monad m => m (a->b) -> a -> m b
fmonad fm a =
     do  { f <- fm
         ; return $ f a
         }

But not all cases I encounter involve lists or monads.  A different case 
might look like this:

 >  eval :: (b->c->d) -> (a->b) -> (a->c) -> (a->d)
 >  eval f g1 g2 a = f (g1 a) (g2 a)

So, for example, a function to test of the two elements of a pair are the 
same might be:

 > pairSame = eval (==) fst snd

giving:

 > pairSame (1,2) -- false
 > pairSame (3,3) -- true

Or a function to subtract the second and subsequent elements of a list from 
the first:

 > firstDiffRest = eval (-) head (sum . tail)

 > firstDiffRest [10,4,3,2,1] -- 0

That's about as far as I've taken this, but it feels as if it might be part 
of a more general pattern.  Hence my question:  is there anything like this 
in the libraries?

#g


------------
Graham Klyne
For email:
http://www.ninebynine.org/#Contact



More information about the Haskell-Cafe mailing list