简体   繁体   中英

Difference between Monads and Functions

Ok, about Monad , I am aware that there are enough questions having been asked. I am not trying to bother anyone to ask what is monad again.

Actually, I read What is a monad? , it is very helpful. And I feel I am very close to really understand it.

I create this question here is just to describe some of my thoughts on Monad and Function, and hope someone could correct me or confirm it correct.


Some answers in that post let me feel monad is a little bit like function .

Monad takes a type, return a wrapper type ( return ), also, it can take a type, doing some operations on it and returns a wrapper type ( bind ).

From my point of view, it is a little bit like function . A function takes something and do some operations and return something.

Then why we even need monad ? I think one of the key reasons is that monad provides a better way or pattern for sequential operations on the initial data/type.

For example, we have an initial integer i . In our code, we need to apply 10 functions f1, f2, f3, f4, ..., f10 step by step, ie, we apply f1 on i first, get a result, and then apply f2 on that result, then we get a new result, then apply f3 ...

We can do this by functions rawly, just like f1 i |> f2 |> f3... . However, the intermediate results during the steps are not consistent; Also if we have to handle possible failure somewhere in middle, things get ugly. And an Option anyway has to be constructed if we don't want the whole process fail on exceptions. So naturally, monad comes in.

Monad unifies and forces the return types in all steps. This largely simplifies the logic and readability of the code (this is also the purpose of those design patterns , isn't it). Also, it is more bullet proof against error or bug. For example, Option Monad forces every intermediate results to be options and it is very easy to implement the fast fail paradigm.

Like many posts about monad described, monad is a design pattern and a better way to combine functions / steps to build up a process.


Am I understanding it correctly?

It sounds to me like you're discovering the limits of learning by analogy. Monad is precisely defined both as a type class in Haskell and as a algebraic thing in category theory; any comparison using "... like ..." is going to be imprecise and therefore wrong.

So no, since Haskell's monads aren't like functions, since they are 1) implemented as type classes, and 2) intended to be used differently than functions.

This answer is probably unsatisfying; are you looking for intuition? If so, I'd suggest doing lots of examples, and especially reading through LYAH . It's very difficult to get an intuitive understanding of abstract things like monads without having a solid base of examples and experience to fall back on.

Why do we even need monads? This is a good question, and maybe there's more than one question here:

  1. Why do we even need the Monad type class? For the same reason that we need any type class.

  2. Why do we even need the monad concept? Because it's useful. Also, it's not a function, so it can't be replaced by a function. (Your example seems like it does not require a Monad (rather, it needs an Applicative)).

    For example, you can implement context-free parser combinators using the Applicative type class. But try implementing a parser for the language consisting of the same string of symbols twice (separated by a space) without Monad, ie:

     aa -> yes ab -> no ab ab -> yes ab ba -> no

    So that's one thing a monad provides: the ability to use previous results to "decide" what to do. Here's another example:

     f :: Monad m => m Int -> m [Char] fm = m >>= \\x -> if x > 2 then return (replicate x 'a') else return [] f (Just 1) -->> Just "" f (Just 3) -->> Just "aaa" f [1,2,3,4] -->> ["", "", "aaa", "aaaa"]

Monads (and Functors , and Applicative Functors ) can be seen as being about " generalized function application": they all create functions of type fa ⟶ fb where not only the "values inside a context", like types a and b , are involved, but also the "context" -- the same type of context -- represented by f .

So "normal" function application involves functions of type (a ⟶ b) , "generalized" function application is with functions of type .函数。 Such functions can too be composed under normal function composition, because of the more uniform types structure: fa ⟶ fb ; fb ⟶ fc ==> fa ⟶ fc fa ⟶ fb ; fb ⟶ fc ==> fa ⟶ fc .

Each of the three creates them in a different way though, starting from different things:

Functors:               fmap  :: Functor     f =>   (a ⟶   b) ⟶ 

Applicative Functors:   (<*>) :: Applicative f => f (a ⟶   b) ⟶ 

Monadic Functors:       (=<<) :: Monad       f =>   (a ⟶ f b) ⟶ 

In practice, the difference is in how do we get to use the resulting value-in-context type, seen as denoting some type of computations .

Writing in generalized do notation,

Functors:      do { x <- a ;            return (g x)   }    g <$> a            -- fmap

Applicative    do { x <- a ; y <- b   ; return (g x y) }    g <$> a <*> b
 Functors:                                                  (\ x -> g x <$> b  ) =<< a

Monadic        do { x <- a ; y <- k x ; return (g x y) }    (\ x -> g x <$> k x) =<< a
 Functors:

And their types,

"liftF1"   :: (Functor     f) => (a ⟶ b)      ⟶ f a ⟶       f b           -- fmap

liftA2     :: (Applicative f) => (a ⟶ b ⟶ c) ⟶ f a ⟶       f b  ⟶ f c

"liftBind" :: (Monad       f) => (a ⟶ b ⟶ c) ⟶ f a ⟶ (a ⟶ f b) ⟶ f c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM