在Haskell代码中解析输入“ if”上的错误

问题描述

我正在尝试使用Haskell,并且对这种编程语言不熟悉。我正在运行这段代码,当函数的整数大于50时,此代码将打印“更大”,而当函数的整数小于50时,则打印“较少”。

return Container(
 width: 200,child: CupertinoTextField(
    maxLength: 10,textCapitalization: TextCapitalization.characters,focusNode: focusNode,decoration: Boxdecoration(
        border: Border.all(color: Colors.white.withOpacity(0))),style: accentTextStyle,placeholder: "NAME",textAlign: TextAlign.center,keyboardAppearance: Brightness.dark,controller: _textController,onChanged: (s) {
      navigation.update();
      if (s == '') {
        program.name = 'UNNAMED${navigation.programsCounter}';
        return;
      }
      program.name = s.toupperCase();
    },),);

但是,当我运行代码时,它给了我这个错误

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

我去了5号线,那条线什么也没有。有谁知道如何解决错误?我将不胜感激!

解决方法

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

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

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

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

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"