Search code examples
haskellparse-error

parse error in pattern


count a []       = 0
count a (b:xs) = c + count a xs
  where c = case b of
          (b==a) -> 1
          (b/=a) -> 0

GHCI gives the error "Parse error in pattern: b == a"

I would like to know why this parse error occurs.

Thank You.


Solution

  • a == b is not a pattern, it's an expression. As the other answer says, something like this will work:

    case a == b of
      True  -> 1
      False -> 0
    

    but that can be written more simply as

    if a == b then 1 else 0
    

    Perhaps you're thinking about pattern guards?

    case a of
      junk | a == b -> 1
           | a /= b -> 0
    

    In general, Haskell offers so many different ways to do conditional branching, it can be confusing to work out which one you need. Patterns are generally for when you want to decide based on which constructor is present, or you want to extract one of the constructor's fields into a variable for something. For comparing values, you generally want an if-expression instead.