4

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!

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The thing about using tabs for indentation is that they're fine on their own, but mixing tabs and spaces leads to misleading situations (e.g. three spaces visually looks like much less indentation than two tabs but is actually more). And since your files will almost certainly include spaces, it's tabs that have to go.
I usually put let and where on their own lines unless the entire scope is going to fit easily on a single line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.