如何使用where子句中的块分配行中的变量? [英] How to use variable from do block assignment line in a where clause?
问题描述
我有以下代码示例:
{-# 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
由于某些原因,我不能在where
子句中使用变量b
,我得到的错误如下:
For some reason I cannot use variable b
in a where
clause, the error I get is the following:
Main3.hs:13:15: error: Variable not in scope: b
|
13 | where c = b^2
| ^
有什么想法可以在where
子句中提供b
吗?
Any ideas how to make b
available in the where
clause?
推荐答案
使用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))
该问题的原因是where
子句中的变量在所有main
的范围内,但是b
在b :: Int <- readLn
之后才在范围内.通常,where
子句不能引用绑定在do
块内部的变量(或=
右侧的任何位置,例如:f x = y*2 where y = x+1
可以,但f = \x -> y*2 where y = x+1
则不能)
The reason for the problem is that variables in the where
clause are in scope for all of main
, but b
isn't in scope until after b :: Int <- readLn
. In general, where
clauses can't reference variables bound inside of a do
block (or anywhere to the right of the =
, for that matter: e.g., f x = y*2 where y = x+1
is fine but f = \x -> y*2 where y = x+1
is not).
这篇关于如何使用where子句中的块分配行中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!