在Haskell中读取函数后出现解析错误

8dtrkrch  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(141)

我目前正在创建一个程序,它从用户那里获取一个数字,然后根据输入决定发生什么:

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)行之后时发生的,我不知道为什么。如果有任何建议,我将不胜感激,提前感谢。

8yparm6h

8yparm6h1#

问题是then块包含多行。对于这些,您可以使用额外的do来执行去糖化。另一个问题是每个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 < yx > yx == 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

相关问题