Why "Parse error in pattern: x >= y" when defining a function by guarded equation?

193 views Asked by At

I try to use guarded equation to define a function. Why does it not work in GHCi? Thanks.

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
1

There are 1 answers

4
bradrn On

Your syntax is wrong. Don’t be confused by the fact that the prompt already contains |! What you’ve written is the following:

maxThree :: Integer -> Integer -> Integer -> Integer
maxThree x y z
x >= y && x >= z = x
y >= z = y
otherwise = z

As you can see, this is clearly wrong. Guards always start with a vertical bar |, but you’ve left it out. I assume you got confused by the fact that the Prelude| prompt already contains |; that is part of the UI of GHCi, and is not considered to be part of the code you type in. If you want to type a guard into GHCi, do it like this:

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| :}

Note how I have typed the code into GHCi exactly the same as I would type it into a file, including the fact that the guards need to be indented relative to the start of the definition.