Is it possible to use guards to define a function after a where is Haskell?
This works fine :
myMax a b = a + b - myMin a b
where myMin a b = if a < b then a else b
But this
myMax a b = a + b - myMin a b
where myMin a b
| a < b = a
| otherwise = b
will throw the following error message in ghci :
parse error (possibly incorrect indentation or mismatched brackets)
on the line corresponding to | a < b = a
Just as well, this will work :
myMax a b =
let myMin a b = if a < b then a else b
in a + b - myMin a b
But this won't :
myMax a b =
let myMin a b
| a < b = b
| otherwise = a
in a + b - myMin a b
My guess would be that it's because using guards does not actually define a variable, even though it is required by the where and let/in structures? I am very new to Haskell so any explanation is greatly welcome!
You have to indent the guards past the declaration of your function:
myMax a b = a + b - myMin a b
where myMin x y -- Also, use different variable names here to avoid conflicts
| x < y = x
| otherwise = y
Or as
myMax a b =
let myMin x y
| x < y = x
| otherwise = y
in a + b - myMin a b
If you're using tabs for indentations, I would highly recommend to using spaces, they're less ambiguous with Haskell. You can use tabs, but I see a lot of people run into parse errors because of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With