通过保护方程式定义函数时,为什么会出现“分析模式中的错误:x> = y”?

Tim*_*Tim -2 syntax haskell function definition guard-clause

我尝试使用保护方程式定义函数。为什么在GHCi中不起作用?谢谢。

Prelude> :{
Prelude| maxThree :: Integer -> Integer -> Integer -> Integer
Prelude| maxThree x y z
Prelude| x >= y && x >= z = x
Prelude| y >= z = y
Prelude| otherwise = z
Prelude| :}

<interactive>:77:1: error: Parse error in pattern: x >= y
Run Code Online (Sandbox Code Playgroud)

bra*_*drn 8

您的语法错误。不要被提示已经包含的事实所迷惑|!您所写的内容如下:

maxThree :: Integer -> Integer -> Integer -> Integer
maxThree x y z
x >= y && x >= z = x
y >= z = y
otherwise = z
Run Code Online (Sandbox Code Playgroud)

如您所见,这显然是错误的。警卫总是以竖线开头|,但是您将其省略了。我认为您对Prelude|提示已经包含的事实感到困惑|;这是GHCi UI的一部分,并且被视为您键入的代码的一部分。如果要在GHCi中键入防护,请按以下步骤操作:

Prelude> :{
Prelude| maxThree :: Integer -> Integer -> Integer -> Integer
Prelude| maxThree x y z
Prelude|   | x >= y && x >= z = x
Prelude|   | y >= z = y
Prelude|   | otherwise = z
Prelude| :}
Run Code Online (Sandbox Code Playgroud)

请注意,我如何将代码键入到GHCi 中与我将其键入文件中完全相同,包括以下事实:需要相对于定义的开头缩进保护符。

  • @bradrn在这种特殊情况下,您不必保持一致。保护符不是块的单独行(它们没有插入隐式分号),因此它们只需要比其封闭的块缩进更多,但是如果您愿意,每行的缩进量都可以与该块不同。 (2认同)