我目前正在創建一個程式,該程式從用戶那里獲取一個數字,然后根據輸入決定會發生什么:
function :: Int -> IO ()
function n = do
putStr "Input: "
x <- getLine
let y = (read x :: Int)
if y == n
then
print "Something"
else if y < n
then
print "Something"
function n
else if y > n
then
print "Something"
function n
但是,上面的代碼回傳一個“ parse error (possibly incorrect indentation or mismatched brackets)”錯誤。當我在該行之后放置任何型別的條件陳述句(if/guard/case)時似乎會發生此錯誤,但let guess = (read x :: Int)我無法弄清楚原因。任何建議將不勝感激,在此先感謝。
uj5u.com熱心網友回復:
問題是then包含多行的塊。對于這些,您可以使用額外do的 s 來執行脫糖。另一個問題是每個都if … then … else …需要一個else …子句,因為這些是運算式,所以沒有陳述句:
function :: Int -> IO ()
function n = do
putStr "Input: "
x <- getLine
let y = (read x :: Int)
if y == n
then
print "Something"
else if y < n
then do
print "Something"
function n
else if y > n
then do
print "Something"
function n
else
pure ()
更簡單的是:
function :: Int -> IO ()
function n = do
putStr "Input: "
x <- getLine
let y = read x
if y == n then print "Something"
else if y < n then print "Something" >> function n
else if y > n then print "Something" >> function n
else pure ()
通常對于兩個專案,它持有x < y, x > yor x == y(盡管Double例如對于 s 不持有)。因此,您可以省略最后一次檢查:
function :: Int -> IO ()
function n = do
putStr "Input: "
x <- getLine
let y = read x
if y == n then print "Something"
else if y < n then print "Something" >> function n
else print "Something" >> function n
如果滿足以下條件,我們還可以使用多種方式:
{-# LANGUAGE MultiWayIf #-}
function :: Int -> IO ()
function n = do
putStr "Input: "
x <- getLine
let y = read x
if
| y == n -> print "Something"
| y < n -> print "Something" >> function n
| otherwise -> print "Something" >> function n
或帶有case … of …:
function :: Int -> IO ()
function n = do
putStr "Input: "
x <- getLine
case read x `compare` n of
EQ -> print "Something"
LT -> print "Something" >> function n
GT -> print "Something" >> function n
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/530205.html
標籤:哈斯克尔
上一篇:Haskell——用空格填充串列
