This post is from a low-reputation account and contains an unverified outbound link. Be cautious before clicking external links.

Understand Functor, Applicative and Monad

Words
353
Reading
2 min
Listen
Play
8y

Functor

  • A Functor is any data type that defines how fmap applies to it.
  • Lists are functors too!
  • Functions are Functors too. When you use fmap on a function, you're just doing function composition!
  • Functors apply a function to a wrapped value

Applicatives

  • Applicatives take it to the next level. With an applicative, our values are wrapped in a context.
  • Applicative pushes Functor aside.
  • Control.Applicative defines <*>
  • Applicatives apply a wrapped function to a wrapped value

Monads

  • Monads apply a function that returns a wrapped value to a wrapped value.
  • Monads have a function >>= (pronounced "bind") to do this.
  • Monad is another typeclass.
  • Maybe is a Functor, an Applicative, and a Monad
  • Haskell also provides us with some syntactical sugar for monads, called do notation

Conclusion

  • Functor, Applicative, Monad are typeclass, the value implements them is one Functor or Applicative or Monad
  • A functor is a data type that implements the Functor typeclass.
  • An applicative is a data type that implements the Applicative typeclass.
  • A monad is a data type that implements the Monad typeclass.
  • A Maybe implements all three, so it is a functor, an applicative, and a monad.
  • syntax sugar
    1. functors: you apply a function to a wrapped value using fmap or <$>
    2. applicatives: you apply a wrapped function to a wrapped value using <*> or liftA
    3. monads: you apply a function that returns a wrapped value, to a wrapped value using >>= or liftM

alt

# normal
f a -> b
# functor: 
f <a> -> <b>
# applicative: 
<f> <a> -> <b>
# monad: f a -> 
<a> (f a -> <b>) -> <b>

所以

  • functor 解包参数
  • applicative 解包函数
  • monad 把一个既不是normal也不是functor情形的函数和一个包裹参数颠倒顺序

另外一种视角

  1. Functor: apply a function to a container.
  2. Applicative: apply a multi-argument function to multiple containers.
  3. Monad: like Applicative but I can decide what to do next after each step.

所以可以把这个 container 看作“更多数量的元素”,把monad看做可中断的流水线。

Links