简体   繁体   English

这个奇怪的单子绑定如何工作?

[英]How does this weird monad bind work?

This is probably a very noob question but I was playing around with the bind operator in Haskell and I encountered a way to repeat a string using it. 这可能是一个非常菜鸟式的问题,但是我在Haskell中玩bind运算符,遇到了一种使用它重复字符串的方法。

[1..3] >>= const "Hey"
-- Yields "HeyHeyHey"
[1..3] >>= return "Hey"
-- Also yields the same result

I understand how >>= (\\_ -> return "Hey") would yield ["Hey", "Hey", "Hey"] but I don't understand why (\\_ -> "Hey") repeats the string or why >>= return "Hey" does the same thing. 我了解>>= (\\_ -> return "Hey")产生["Hey", "Hey", "Hey"]但我不明白为什么(\\_ -> "Hey")重复该字符串还是为什么>>= return "Hey"做同样的事情。

I understand how >>= (\\_ -> return "Hey") would yield ["Hey", "Hey", "Hey"] 我了解>>= (\\_ -> return "Hey")产生["Hey", "Hey", "Hey"]

right. 对。 return "Hey" is in this case the same as ["Hey"] , because 在这种情况下, return "Hey"["Hey"] ,因为

instance Monad [] where
  return x = [x]

So 所以

([1..3] >>= \_ -> return "Hey")
  ≡  ([1..3] >>= \_ -> ["Hey"])
  ≡  ["Hey"] ++ ["Hey"] ++ ["Hey"]
  ≡  ["Hey", "Hey", "Hey"]

Now, >>= (\\_ -> "Hey") can also be be written with a list-result in the lambda, because strings are just lists of characters. 现在, >>= (\\_ -> "Hey")也可以用lambda中的列表结果写入,因为字符串只是字符列表。

([1..3] >>= \_ -> "Hey")
  ≡  ([1..3] >>= \_ -> ['H','e','y'])
  ≡  ['H','e','y'] ++ ['H','e','y'] ++ ['H','e','y']
  ≡  ['H','e','y','H','e','y','H','e','y']
  ≡  "HeyHeyHey"

As for >>= return "Hey" , that's a different beast. 至于>>= return "Hey" ,那是另一种野兽。 The return belongs to a completely different monad here, namely the function functor . return在这里属于完全不同的monad,即函数functor

instance Monad (x->) where
  return y = const y

Hence it's kind of clear that ([1..3] >>= const "Hey") and ([1..3] >>= return "Hey") give the same result: in that example, return is just another name for const ! 因此,很显然([1..3] >>= const "Hey")([1..3] >>= return "Hey")给出相同的结果:在该示例中, return只是另一个const名字!

The return being used here is not for the list monad, but for the function monad, in which this definition holds: 这里使用的return值不是用于列表monad,而是用于函数monad,该函数包含以下定义:

return x = \_ -> x

So this is the same as: 因此,这与以下内容相同:

[1,2,3] >>= (\_ -> "Hey")

and since (>>=) is the same as concatMap for lists, we have: 并且(>>=)与清单的concatMap相同,因此我们有:

concatMap (\_ -> "Hey") [1,2,3]

Can you see why this yields "HeyHeyHey" ? 您知道为什么会产生"HeyHeyHey"吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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