【问题标题】:Error on my Haskell code我的 Haskell 代码出错
【发布时间】:2014-07-18 04:09:29
【问题描述】:

我的代码出现此错误:

“解析错误(可能是不正确的缩进或不匹配的括号)”

max3 a b c = if a>b && a>c then show a
     else if b>a && b>c then show b
     else if c>a && c>b then show c

我需要在 a、b 和 c 之间取较大的数字

编辑:按照建议添加 else 子句后:

max3 a b c = if a>b && a>c then show a
     else if b>a && b>c then show b
     else if c>a && c>b then show c
     else show "At least two numbers are the same"

现在我收到此错误“输入 `if' 时出现解析错误”

按照建议编辑!

已编辑:已解决,我对 说的守卫做了!太棒了!

【问题讨论】:

  • 你需要一个最终的“else”。或者你可以使用maximum [a,b,c]
  • 其实是“至少两个数相同”。
  • otherwise 与警卫一起工作,而不是 if...else
  • 那么为什么在我的第一个案例中出现解析错误? x_x
  • 您当前的代码加载对我来说很好。也许您的文件中还有其他问题会导致问题?

标签: shree.pat18 parsing haskell


【解决方案1】:

正如 John L 在 cmets 中提到的,您需要一个最终的 else 子句来捕捉您的条件都不为真的情况。

或者,您可以使用守卫代替if..else if,如下所示:

max3 a b c 
          | a > b && a > c = show a
          | b > a && b > c = show b
          | c > a && c > b = show c
          | otherwise = show "At least two numbers are the same"

【讨论】:

  • max3 a b c if a>b && a>c then show a else if b>a && b>c then show b else if c>a && c>b then show c else show "The numbers是一样的”我在其他地方添加,现在出现这个“输入'if'时出现解析错误”
  • 请将更新后的代码添加到您的问题中。另外,您是否尝试过我更新的使用警卫的代码?
  • 条件并非详尽无遗。 a=b=2,c=1。始终使用otherwise
  • 我使用了其他方法,但我仍然收到错误“输入 `if' 时解析错误”
【解决方案2】:
import Data.List (maximum)

max3 a b c = maximum [a, b, c]

Fuhgeddaboudit.

【讨论】:

  • 我需要创建函数,这是我课堂上需要的练习!
  • 但是,您确实创建了函数。为什么你可以使用show&&>,它们都是由标准库(不是语言)定义的,但你不能使用同样由标准库定义的maximum
猜你喜欢
  • 2015-01-07
  • 2016-02-24
  • 2017-11-20
  • 2013-01-07
  • 2022-01-23
  • 2021-12-09
  • 2015-03-29
  • 2020-07-25
  • 1970-01-01
相关资源
最近更新 更多