gpt4 book ai didi

haskell - GHCI monadic 绑定(bind)是否严格?

转载 作者:行者123 更新时间:2023-12-02 02:50:24 25 4
gpt4 key购买 nike

GHC 手册说明了 GHCI 中的一元绑定(bind):

Another important difference between the two types of binding is that the monadic bind (p <- e) is strict (it evaluates e), whereas with the let form, the expression isn’t evaluated immediately:



(来自 here)

但我可以在 GHCI 中做到这一点:
λ: x <- return $ error ":("
λ: :sprint x
x = _

这似乎表明一元绑定(bind)并不严格。我错过了什么?

最佳答案

请记住,严格的函数意味着 f ⊥ = ⊥ .考虑:

ghci> x <- return undefined
-- no error

这意味着 return undefined >>= \x -> ...不是⊥,但这并没有真正说明 >>=的严格性。 ,因为 return .然而,这:
ghci> y <- undefined
*** Exception: Prelude.undefined

是手册所指的情况,它表明绑定(bind)在左侧参数中是严格的,因为 undefined >>= (\y -> ...)是⊥。最后,
ghci> :set -XBangPatterns
ghci> !z <- return undefined
*** Exception: Prelude.undefined

这一行显示了如果我们给它一个严格的函数作为参数会发生什么,所以我们知道 return undefined >>= f是 ⊥ 如果 f是严格的。这实际上遵循单子(monad)定律 return x >>= f = f x , 所以 return ⊥ >>= f = f ⊥ = ⊥

关于haskell - GHCI monadic 绑定(bind)是否严格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48454609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com