【问题标题】:parse error on input ‘if’ in Haskell code在 Haskell 代码中输入“if”时解析错误
【发布时间】:2021-02-09 02:13:24
【问题描述】:

我正在尝试使用 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 行,行中什么都没有。有谁知道此时如何解决此错误?我会很感激的!

【问题讨论】:

    标签: if-statement haskell syntax syntax-error function-definition


    【解决方案1】:

    您的函数子句没有“头”。您需要指定函数的名称和可选模式:

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

    但这仍然有效。 Thre 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"

    【讨论】:

      【解决方案2】:

      你可能想要这样的东西:

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

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

      使用if 可以解决此问题,但请注意,守卫也是一种常见的替代方法。

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

      【讨论】:

        猜你喜欢
        • 2018-05-02
        • 2014-02-07
        • 2016-01-11
        • 2017-08-16
        • 1970-01-01
        • 2013-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多