繁体   English   中英

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

[英]How does this weird monad bind work?

这可能是一个非常菜鸟式的问题,但是我在Haskell中玩bind运算符,遇到了一种使用它重复字符串的方法。

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

我了解>>= (\\_ -> return "Hey")产生["Hey", "Hey", "Hey"]但我不明白为什么(\\_ -> "Hey")重复该字符串还是为什么>>= return "Hey"做同样的事情。

我了解>>= (\\_ -> return "Hey")产生["Hey", "Hey", "Hey"]

对。 在这种情况下, return "Hey"["Hey"] ,因为

instance Monad [] where
  return x = [x]

所以

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

现在, >>= (\\_ -> "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"

至于>>= return "Hey" ,那是另一种野兽。 return在这里属于完全不同的monad,即函数functor

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

因此,很显然([1..3] >>= const "Hey")([1..3] >>= return "Hey")给出相同的结果:在该示例中, return只是另一个const名字!

这里使用的return值不是用于列表monad,而是用于函数monad,该函数包含以下定义:

return x = \_ -> x

因此,这与以下内容相同:

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

并且(>>=)与清单的concatMap相同,因此我们有:

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

您知道为什么会产生"HeyHeyHey"吗?

暂无
暂无

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

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