为什么Haskell monadic绑定左关联?

时间:2018-03-24 21:37:00

标签: haskell monads

>>=>>运算符均为infixl 1。为什么左关联?

特别是,我观察到等价:

(do a; b; c ) == (a >> (b >> c))   -- Do desugaring
(a >> b >> c) == ((a >> b) >> c)   -- Fixity definition

所以do与固定性定义的自然运作方式不同,这是令人惊讶的。

2 个答案:

答案 0 :(得分:14)

>>=肯定是左联想的。

Prelude> ["bla","bli di","blub"] >>= words >>= reverse
"albilbidbulb"
Prelude> ["bla","bli di","blub"] >>= (words >>= reverse)

<interactive>:3:30: error:
    • Couldn't match expected type ‘[[b0]]’
                  with actual type ‘String -> [String]’
    • Probable cause: ‘words’ is applied to too few arguments
      In the first argument of ‘(>>=)’, namely ‘words’
      In the second argument of ‘(>>=)’, namely ‘(words >>= reverse)’
      In the expression:
        ["bla", "bli di", "blub"] >>= (words >>= reverse)

>>几乎跟随>>=;如果它有另一个固定性,它不仅会像Lennart所说的那样感觉很奇怪,它也会阻止你在链条中使用这两个运算符:

Prelude> ["bla","bli di","blub"] >>= words >> "Ha"
"HaHaHaHa"
Prelude> infixr 1 ⬿≫; (⬿≫) = (>>)
Prelude> ["bla","bli di","blub"] >>= words ⬿≫ "Ha"

<interactive>:6:1: error:
    Precedence parsing error
        cannot mix ‘>>=’ [infixl 1] and ‘⬿≫’ [infixr 1] in the same infix expression

答案 1 :(得分:6)

>>=是左关联的,因为它很方便。我们希望将m >>= f1 >>= f2解析为(m >>= f1) >>= f2,而不是m >>= (f1 >>= f2),这可能不会进行类型检查,如评论中所述。

>>的相关性只是>>=的一面镜子。这可能是为了保持一致,因为我们可以通过第三个monad定律证明>>是关联的:(m >>= f) >>= g ≡ m >>= ( \x -> f x >>= g )。也就是说,它的相关性在理论上并不重要。以下是证据:

-- Definition:
a >> b ≡ a >>= (\_ -> b)

-- Proof: (a >> b) >> c ≡ a >> (b >> c)
  (a >> b) >> c
≡ (a >>= (\_ -> b)) >> c                  -- [Definition]
≡ (a >>= (\_ -> b)) >>= (\_ -> c)         -- [Definition]
≡ a >>= (\x -> (\_ -> b) x >>= (\_ -> c)) -- [Monad law]
≡ a >>= (\_ -> b >>= (\_ -> c))           -- [Beta-reduction]
≡ a >>= (\_ -> b >> c)                    -- [Definition]
≡ a >> (b >> c)                           -- [Definition]
∎

do - 符号表示不同,因为它有不同的目标。从本质上讲,由于do-notation本质上是写出lambda,因此需要正确的关联。这是因为m >>= (\v -> (...))被写为do {v <- m; (...)}。如前所述,为了保持一致性,此处>>的去糖似乎遵循>>=

相关问题