Search code examples
haskellfunctorapplicative

(<*>) without having to wrap the second argument


Haskell newbie here. So (<$>) is defined as

(<$>) :: Functor f => (a -> b) -> f a -> f b

And (<*>) is defined as

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

But I feel like Applicative is two concepts in one:

  1. One would be that of a functor
  2. And one would be this:
(<@>) :: MyConcept m => m (a -> b) -> a -> b

So e.g. thinking in terms of Maybe:

I have an let i = 4 and I have a let foo = Nothing :: Num a => Maybe (a -> a). Basically I have a function that may or may not be there, that takes an Int and returns an Int, and an actual Int.

Of course I could just wrap i by saying:

foo <*> Just i

But that requires me to know the what Applicative foo is wrapped in. Is there something equivalent to what I described here? How would I go about implementing that function <@> myself?

It would be something like this:

let (<@>) func i = func <*> ??? i

Solution

  • You can use pure:

    pure :: Applicative f => a -> f a
    
    foo <*> pure i
    

    although you could just use fmap:

    fmap (\f -> f i) foo
    

    or

    fmap ($ i) foo