문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top