[英]Why is Haskell monadic bind left-associative?
>>=
和>>
運算符都是infixl 1
。 為什么左關聯?
特別是,我觀察到等價:
(do a; b; c ) == (a >> (b >> c)) -- Do desugaring
(a >> b >> c) == ((a >> b) >> c) -- Fixity definition
對於固定性定義如何自然地起作用,這樣do
是不同的,這是令人驚訝的。
>>=
肯定是左聯想的。
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
>>=
是左關聯的,因為它很方便。 我們希望m >>= f1 >>= f2
被解析為(m >>= f1) >>= f2
,而不是m >>= (f1 >>= f2)
,這可能不會像指向那樣進行類型檢查在評論中。
然而, >>
的相關性只是>>=
的鏡像。 這可能是為了保持一致,因為我們可以證明>>
通過第三個monad定律是關聯的: (m >>= f) >>= g ≡ m >>= ( \\x -> fx >>= 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
-notation不同,因為它有不同的目標。 從本質上講,由於do-notation本質上是寫出lambda,因此需要正確的關聯。 這是因為m >>= (\\v -> (...))
寫成do {v <- m; (...)}
do {v <- m; (...)}
。 如前所述,為了保持一致性, >>
的脫糖似乎遵循>>=
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.