haskell : unexpected ´;' possibly due to bad layout

标签 haskell syntax-error

我必须编写一个简单的程序来告诉我,有多少个解有一个二次方程。我写道:

howManySolutions :: Float -> Float -> Float -> Int

howManySolutions a b c = if (b^2-(4*a*c)) > 0 then 2 else 
                         if (b^2-(4*a*c)) == 0 then 1
                         else -1

但在 WinHugs 中我收到语法错误:

  unexpected ´;' possibly due to bad layout

我可以在 GHCi 中打开我的程序,但它不允许我使用负数...我做错了什么?

最佳答案

我不确定 winhugs 问题,但我可以帮助您解决 ghci 问题。

首先,一点缩进:

howManySolutions a b c = if (b^2-(4*a*c)) > 0
                         then 2
                         else 
                           if (b^2-(4*a*c)) == 0
                           then 1
                           else -1

现在,如果您尝试在 ghci 中输入 howManySolutions -1 2 3,您会得到 No instance for (Num (Float -> Float -> Float -> Int))使用“-”。基本上,它将“-”解释为应用于 1 2 和 3 的函数,而不是仅将其应用于“1”。

您所需要做的就是输入 howManySolutions (-1) 2 3

现在,如果我可以给你一个提示,像这样的模式通常处理的方式是这样的:

howManySolutions a b c
  | delta > 0 = 2
  | delta == 0 = 1
  | otherwise = -1
  where delta = b^2-4*a*c 

“|”符号(守卫)充当不同的“if”,底部的“where”子句允许您定义一次增量,以便在守卫中多次重用。更漂亮了:D

关于 haskell : unexpected ´;' possibly due to bad layout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19799482/

相关文章:

haskell - 为什么镜头包含用于 fromEnum/toEnum 的 Iso,而不包含用于显示/读取的 Iso?

python - Python Turtle write()语法错误

c - 错误 : A compound literal of type not allowed

haskell - Haskell 中数据传输记录的通用类型

c - haskell C FFI : accessing static data structures

sorting - 编写排序实例的有效方法?

syntax - Linden脚本语言怪异语法错误

sql - 如何将单个日期分为几个月

php - PHP语法错误由引号引起

opengl - 如何使用 opengl 在 Haskell 中绘制圆圈