Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard function that computes `f x (g x)`?

Tags:

haskell

I couldn't find anything on Hoogle, but is there a standard function or operator with a signature like:

func :: (a -> b -> c) -> (a -> b) -> a -> c

I.e. given two functions f and g and an element x as arguments it computes f x (g x)?

like image 641
mschmidt Avatar asked Nov 30 '22 08:11

mschmidt


1 Answers

The function you’re looking for is (<*>). Why? Well, it’s true that (<*>) has a more general type:

(<*>) :: Applicative f => f (a -> b) -> f a -> f b

But consider that we can specialize f to (->) r, which has an Applicative instance:

(<*>) :: (->) r (a -> b) -> (->) r a -> (->) r b

…then we can rearrange the type so -> is infix instead of prefix, as it normally is:

(<*>) :: (r -> a -> b) -> (r -> a) -> (r -> b)

…which is the same as your signature modulo alpha renaming.

This works because the function type, (->), has instances of Functor, Applicative, and Monad, which are idiomatically called “reader”. These instances thread an extra argument around to all their arguments, which is exactly what your function does.

like image 72
Alexis King Avatar answered Dec 09 '22 23:12

Alexis King