gpt4 book ai didi

haskell - 如何在Haskell中的IO()函数中用 "let/in"替换 "where"构造?

转载 作者:行者123 更新时间:2023-12-04 12:30:33 24 4
gpt4 key购买 nike

我正在学习 Haskell 并尝试我的第一个 IO 函数。这是一个计算矩形面积的简单程序,它运行良好:

squareCalc :: IO ()
squareCalc = do
putStrLn "Pease enter the lenght"
length <- getLine
putStrLn "Pleas enter the width"
width <- getLine
let square = read length * read width
in putStrLn ("The square is " ++ show square)

但是,当我尝试将“let/in”替换为“where”时:

squareCalc2 :: IO ()
squareCalc2 = do
putStrLn "Pease enter the lenght"
length <- getLine
putStrLn "Pleas enter the width"
width <- getLine
putStrLn ("The square is " ++ show square)
where
square = (read length) * (read width)

编译器返回错误错误:

Variable not in scope: width :: String

我想知道是否可以在这样的函数中使用“where”?

最佳答案

缩进的方式

putStrLn ("The square is " ++ show square) 
where
square = (read length) * (read width)

让我认为您希望将此代码视为表达式。问题在于 where 在表达式中不合法。它仅在变量/函数/模式绑定(bind)的右侧之后才合法。

您可能希望得到一个语法错误,但这不是布局规则的工作原理。当解析器遇到语法错误,并且布局规则中有一个开放的隐式大括号 block 时,它将关闭该 block 以尝试使错误消失。在这种情况下,它有效:您的代码变成

squareCalc2 = do
{ ... }
where
square = (read length) * (read width)

这在语法上是有效的。但是 lengthwidth 仅在大括号内的范围内,因此编译无论如何都会失败。

请注意,为了方便起见,在 do block 中允许不带 inlet,因此您可以这样写:

squareCalc = do
...
let square = read length * read width
putStrLn ("The square is " ++ show square)

关于haskell - 如何在Haskell中的IO()函数中用 "let/in"替换 "where"构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69398517/

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