alt*_*ern 5 monads haskell scope where-clause do-notation
我有以下代码示例:
{-# LANGUAGE ScopedTypeVariables #-}
main = do
putStrLn "Please input a number a: "
a :: Int <- readLn
print a
putStrLn "Please input a number b: "
b :: Int <- readLn
print b
putStrLn ("a+b+b^2:" ++ (show $ a+b+c))
where c = b^2
Run Code Online (Sandbox Code Playgroud)
由于某种原因,我不能b在where子句中使用变量,我得到的错误如下:
Main3.hs:13:15: error: Variable not in scope: b
|
13 | where c = b^2
| ^
Run Code Online (Sandbox Code Playgroud)
任何想法如何b在where条款中提供?
Jos*_*ica 15
使用let代替where:
{-# LANGUAGE ScopedTypeVariables #-}
main = do
putStrLn "Please input a number a: "
a :: Int <- readLn
print a
putStrLn "Please input a number b: "
b :: Int <- readLn
print b
let c = b^2
putStrLn ("a+b+b^2:" ++ (show $ a+b+c))
Run Code Online (Sandbox Code Playgroud)
问题的原因是where子句中的变量在所有 of 的范围内main,但b在 之后才在范围内b :: Int <- readLn。通常,where子句不能引用do块内绑定的变量(或 右侧的任何地方=,就此而言:例如,f x = y*2 where y = x+1很好但f = \x -> y*2 where y = x+1不是)。