Home > Enterprise >  how do I get past the "parse error on input ‘|’" error?
how do I get past the "parse error on input ‘|’" error?

Time:06-11

I'm new to Haskell and code in general and while trying to write a script that shows which of two numbers is smaller to practise using guards i got stuck with the "parse error on input ‘|’" error. I read about using "let" somehow but I haven't been able to figure it out. How do I get past this error?

smallest a b = | a >= b = b
               | a <= b = a

CodePudding user response:

I'm posting this answer to clarify that you do need the equal sign; but you need one for each case, whereas you essentially duplicated it:

--                       --- this is the equal sign (one per case)
--                      |
--            ----------|--- which you are duplicating here
--           |          |
--           v          v
smallest a b = | a >= b = b
               | a <= b = a

that's the reason why the suggested code works.

By the way, the indentation is important, but you can write that snippet on 2 lines rather than 3,

smallest a b | a >= b = b
             | otherwise = a

though it does not improve readability, and actually decreseas it if the part before the first | is long.

By the way, as far as I remember, otherwise is truly just a synonym for True (well, the former is a function, and the latter a value constructor, but I guess this makes little difference, as the former is like a 0-arguments function that generates the latter, so they are fundamentally synonyms).

CodePudding user response:

When using guards, you don't need the equals sign. You can simply do this:

smallest a b 
    | a >= b = b
    | otherwise = a

Note the indentation here. Also, since your first condition takes care of both the greater than and equal cases, you can simply use "otherwise" instead of explicitly stating the remaining case.

  • Related