roam/20220316185946-applicative.org
2022-03-16 19:56:10 -04:00

1.4 KiB

Applicative

In Software Development, this refers to a Functor that provides a method for applying a function wrapped in such a type to a value wrapped in the same type.

In Haskell, the function for applying a wrapped function to a value wrapped in the same type is available as the infix operator <*>, and facilitates the application of a function taking an arbitrary number of arguments over multiple wrapped values. An applicative must also implement the pure function, which takes a single argument and returns it wrapped.

  pure :: Applicative f => a -> f a
  (<*>) :: Applicative f => f (a -> b) -> f a -> f b
Applicative functions in Haskell

In the following example, fmap (<$>) first applies the add function to the value Just 1, resulting in a function of the type Just (Int -> Int). The applicative infix operator (<*>) then applies that function to the remaining value Just 2, resulting in Just 3.

  add :: Int -> Int -> Int
  add x y = x + y

  add <$> Just 1 <*> Just 2
Applying a function over multiple wrapped values
Prelude> Just 3