Applicative

An Applicative is like a Functor but in addition it allows you to specify a function to apply to the value in the context, you can supply a function that is in itself inside a context. If you have a list of values and have generated a list of functions to apply to each value, then you can use an Applicative to apply those functions to the list of values. This situation comes up surprisingly often. You could even model your entire program this way. One operation that is really important is the ability to lift a value into the context. This is often expressed as a function named point. point is sometimes called pure, return or unit.

In scalaz, an Applicative Functor is denoted by Applicative directly.

In this example below, we show how you can lift a value into the context using point:

scala> val a = Applicative[List]
val a = Applicative[List]
a: scalaz.Applicative[List] = scalaz.std.ListInstances$$anon$1@1f8d2783

scala> a.point(1)
a.point(1)
res31: List[Int] = List(1)

scala> a.map(a.point(1))(_+1)
a.map(a.point(1))(_+1)
res33: List[Int] = List(2)

to apply a function in an environment to a value in an environment we use Applicative's ap method. First we show what a function in a context looks like then we show the use of ap:

scala> List({i:Int => i + 1})
List({i:Int => i + 1})
res36: List[Int => Int] = List(<function1>)

scala> a.ap(a.point(1))(List{i:Int => i+1})
a.ap(a.point(1))(List{i:Int => i+1})
res38: List[Int] = List(2)

Which seems like alot of work. But if your list of functions need to be applied to a value in a context, then you can think of the functions as a series of operations to be applied to that value.

scala> a.ap(a.point(1))(List({i:Int => i+1}, {i:Int => i-1}))
a.ap(a.point(1))(List({i:Int => i+1}, {i:Int => i-1}))
res40: List[Int] = List(2, 0)

Last updated