If statement 输入上的分析错误‘;如果’;在Haskell代码中
我正在尝试使用Haskell,我对这种编程语言是新手。我正在运行这段代码,当函数的整数大于50时,它打算打印更大的值;当函数的整数小于50时,它打算打印更小的值If statement 输入上的分析错误‘;如果’;在Haskell代码中,if-statement,haskell,syntax,syntax-error,function-definition,If Statement,Haskell,Syntax,Syntax Error,Function Definition,我正在尝试使用Haskell,我对这种编程语言是新手。我正在运行这段代码,当函数的整数大于50时,它打算打印更大的值;当函数的整数小于50时,它打算打印更小的值 printLessorGreater :: Int -> String if a > 50 then return ("Greater") else return ("Less") main = do print(printL
printLessorGreater :: Int -> String
if a > 50
then return ("Greater")
else return ("Less")
main = do
print(printLessorGreater 10)
但是,当我运行代码时,它给了我以下错误:
main.hs:2:5: error: parse error on input ‘if’
我去了5号线,线里什么也没有。现在有人知道如何解决这个错误吗?我会很感激的 您的function子句没有“head”。您需要指定函数的名称,并使用可选模式:
printLessorGreater :: Int -> String
printLessorGreater a = if a > 50 then return ("Greater") else return ("Less")
但这仍然行不通。Threreturn
不等同于命令式语言中的return
语句。以一元类型注入值。虽然列表是一元类型,但如果使用列表单子,则在这种情况下,只能将return
与Char
acter一起使用
因此,您应该将其改写为:
printLessorGreater :: Int -> String
printLessorGreater a = if a > 50 then "Greater" else "Less"
你可能想要这样的东西:
printLessorGreater :: Int -> String
printLessorGreater a = if a > 50
then "Greater"
else "Less"
请注意,这实际上并不打印任何内容,只返回一个字符串
如果使用,则可以使用,但请注意,防护装置也是一种常见的选择
printLessorGreater :: Int -> String
printLessorGreater a | a > 50 = "Greater"
| otherwise = "Less"
printLessorGreater :: Int -> String
printLessorGreater a | a > 50 = "Greater"
| otherwise = "Less"