Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applicative Functor on Lists

I understand that following will be:

[(+2),(+1)]<*>[1,2,3] == [3,4,5,2,3,4]

I also understand that fmap is implemented as map. But how could I mentally map this computation in my head? The first time I saw this I assumed the following:

[(*2),(+1)]<*>[1,2,3] == [4,5,6]

The second time around I though about: [[3,4,5],[2,3,4]]. But on the other hand <*> returns an f b so I knew it wouldn't be possible. So my question is, what are the mental steps to make sense out of this?

like image 584
Rui Peres Avatar asked Dec 17 '14 00:12

Rui Peres


People also ask

What is the difference between a functor and an applicative?

Is a functor, which means that it has a unary (i.e. single-argument) map function (and, thus, an infix version of the same function, called <!> ). Provides a way to apply arguments one at a time, via a <*> function. Provides a way to " lift " values into the applicative. F#'s Option<'t> type is an applicative:

What are applicatives in F #?

In this post, I'd like to dive deeper into the practical usage of applicatives in F#. We described an applicative as a type that: Is a functor, which means that it has a unary (i.e. single-argument) map function (and, thus, an infix version of the same function, called <!> ).

What is an applicative?

We described an applicative as a type that: Is a functor, which means that it has a unary (i.e. single-argument) map function (and, thus, an infix version of the same function, called <!> ). Provides a way to apply arguments one at a time, via a <*> function. Provides a way to " lift " values into the applicative.

Are applicatives monads or functors?

In fact, instead of thinking of applicatives as souped-up functors, it's often easier to think of them as a "lite" version of monads. 2 Let's see where this notion takes us, starting with a basic computation builder for options: Using this builder, we can create monadic computation expressions, such as:


2 Answers

fs <*> xs is more-or-less [f x | f <- fs, x <- xs]. Monads have the Applicative instance

fM <*> xM = do 
  f <- fM
  x <- xM
  return (f x)

which corresponds to the list comprehension pretty directly.

like image 87
Louis Wasserman Avatar answered Sep 24 '22 17:09

Louis Wasserman


To remember this you might find it easier to simply imagine <*> to be × (Cartesian product):

[a, b, c] × [x, y, z] == [a x, a y, a z, b x, b y, ...]
like image 34
Shoe Avatar answered Sep 21 '22 17:09

Shoe