fmap和bind之间的差异? [英] Difference in capability between fmap and bind?

查看:113
本文介绍了fmap和bind之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是功能性编程新手(来自javascript),我很难说出两者之间的差异,这也会让我对函数与monads的理解混乱。



Functor:

$ p $ 类Functor f其中
fmap ::(a - > ; b) - > f a - > fb

Monad(简体):

  class Monad m其中
(>> =):: ma - > (a - > m b) - > mb




  • fmap 接受一个函数和一个函子,并返回一个函子。

  • >> = 返回一个monad。



两者之间的区别在函数参数中:


  • fmap - (a - > b)

  • >> = - (a - > mb)



>> = 取一个返回monad的函数参数。我知道这很重要,但我很难看出这个轻微的东西让单子变得比仿函数强大得多。有人可以解释吗?

解决方案

好吧,(< $>) fmap 的别名,并且(=<<)(>> =)与参数交换:

 (< $> )::(x  - > y) - > b x  - > b y 
(=<<)::(x - > b y) - > b x - >通过

现在这个区别非常明显:使用bind函数,我们应用一个函数, code> by 而不是 y 。那么这有什么不同?



考虑这个小例子:

  foo< $>只要3 

注意(< $>)会将 foo 应用于 3 ,并将结果放回到 Just 。换句话说,这个计算的结果不能是 Nothing 。相反:

  bar =<<只要3 

这个计算可以返回 Nothing 。 (例如, bar x = Nothing 会做到。)



我们可以用列表做类似的事情monad:

  foo< $> [红色,黄色,蓝色]  - 结果保证是一个3元素列表。 
bar =<< [红色,黄色,蓝色] - 结果可以是任意大小。

总之,使用(< $>)(即 fmap ),结果的结构始终与输入相同。但是用(= <)(即(>> =)),结构结果可能会改变。这允许有条件的执行,对输入做出反应,以及其他许多事情。

I'm new to functional programming (coming from javascript), and I'm having a hard time telling the difference between the two, which is also messing with my understand of functors vs. monads.

Functor:

class Functor f where
    fmap :: (a -> b) -> f a -> f b

Monad (simplified):

class Monad m where
    (>>=) :: m a -> (a -> m b) -> m b

  • fmap takes a function and a functor, and returns a functor.
  • >>= takes a function and a monad, and returns a monad.

The difference between the two is in the function parameter:

  • fmap - (a -> b)
  • >>= - (a -> m b)

>>= takes a function parameter that returns a monad. I know that this is significant, but I'm having difficulty seeing how this one slight thing makes monads much more powerful than functors. Can someone explain?

解决方案

Well, (<$>) is an alias for fmap, and (=<<) is the same as (>>=) with the arguments swapped:

(<$>) :: (x ->   y) -> b x -> b y
(=<<) :: (x -> b y) -> b x -> b y

The difference is now fairly clear: with the bind function, we apply a function that returns a b y rather than a y. So what difference does that make?

Consider this small example:

foo <$> Just 3

Notice that (<$>) will apply foo to 3, and put the result back into a Just. In other words, the result of this computation cannot be Nothing. On the contrary:

bar =<< Just 3

This computation can return Nothing. (For example, bar x = Nothing will do it.)

We can do a similar thing with the list monad:

foo <$> [Red, Yellow, Blue]   -- Result is guaranteed to be a 3-element list.
bar =<< [Red, Yellow, Blue]   -- Result can be ANY size.

In short, with (<$>) (i.e., fmap), the "structure" of the result is always identical to the input. But with (=<<) (i.e., (>>=)), the structure of the result can change. This allows conditional execution, reacting to input, and a whole bunch of other things.

这篇关于fmap和bind之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆