Haskell代码中的输入"if"出现解析错误



我正在尝试使用Haskell,而且我是这个编程语言的新手。我正在运行这段代码,当函数的整数大于50时,它将打印Greater,当函数运行的整数小于50时,将打印Less。

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号线,但线路上什么都没有。现在有人知道如何解决这个错误吗?我会很感激的!

您的函数子句没有"头";。您需要指定函数的名称,并使用可选模式:

printLessorGreater :: Int -> String
printLessorGreater a = if a > 50 then return ("Greater") else return ("Less")

但这仍然不起作用。return与命令式语言中的return语句不等价return :: Monad m => a -> m a在一元类型中注入一个值。虽然列表是单元类型,但如果使用列表单元,则在这种情况下只能将returnCharacter一起使用。

因此,您应该将其重写为:

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 = if a > 50
then "Greater"
else "Less"

请注意,这实际上并没有打印任何内容,只是返回一个字符串。

使用if可以做到这一点,但请注意,防护也是一种常见的选择。

printLessorGreater :: Int -> String
printLessorGreater a | a > 50    = "Greater"
| otherwise = "Less"

相关内容

最新更新