gpt4 book ai didi

Haskell:where 子句中的绑定(bind)变量

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

绑定(bind)变量的范围是什么?为什么我无法从 where 子句中访问它?例如,在本例中:

someFunc x y = do
let a = x + 10
b <- someAction y
return subFunc
where
subFunc = (a * 2) + (b * 3)

这里,subFunc 可以看到 a 但看不到 b。为什么不能在 where 子句中使用绑定(bind)变量?谢谢。

最佳答案

因为这可能会导致不一致。想象一下这段代码:

printName = do
print fullName
firstName <- getLine
lastName <- getLine
return ()
where
fullName = firstName ++ " " + lastName

此代码不起作用,并且由于这些情况,绑定(bind)变量的使用仅限于实际绑定(bind)之后的 do block 部分。当对上面的代码进行脱糖处理时,这一点就变得很清楚:

printName =
print fullName >>
getLine >>= (\ firstName ->
getLine >>= (\ lastName ->
return ()
)
)
where
fullName = firstName ++ " " ++ lastName

在这里,我们可以看到变量 firstNamelastName 不在 where 子句的范围内,并且不能使用它们在该子句的任何定义中。

关于Haskell:where 子句中的绑定(bind)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10167867/

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