我必须编写一个简单的程序来告诉我,有多少个解有一个二次方程。我写道:
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/