我正在學習 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)
但是,當我嘗試用“where”替換“let/in”時:
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)
編譯器回傳錯誤錯誤:
變數不在范圍內:width :: String
我想知道是否有可能在這樣的函式中使用“where”?
uj5u.com熱心網友回復:
你縮進的方式
putStrLn ("The square is " show square)
where
square = (read length) * (read width)
讓我認為您希望將此代碼視為運算式。問題是這where在運算式中是不合法的。只有在變數/函式/模式系結的右側之后才是合法的。
您可能會期望得到一個語法錯誤,但這不是布局規則的作業方式。當決議器遇到語法錯誤,并且布局規則中有一個打開的隱式花括號塊時,它會關閉該塊以嘗試使錯誤消失。在這種情況下,它有效:您的代碼變為
squareCalc2 = do
{ ... }
where
square = (read length) * (read width)
這在語法上是有效的。但是lengthandwidth只在大括號內的范圍內,所以編譯無論如何都會失敗。
請注意,為了方便起見,塊中允許let沒有,因此您可以這樣寫:indo
squareCalc = do
...
let square = read length * read width
putStrLn ("The square is " show square)
uj5u.com熱心網友回復:
不,這是不可能的。惱人的。你能得到的最接近的是讓where塊中的東西成為一個函式。
squareCalc2 = do
...
putStrLn ("The square is " show (square length width))
where square length width = read length * read width
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/316873.html
標籤:哈斯克尔
下一篇:Haskell函式格式
