Question

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.

Was it helpful?

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.

OTHER TIPS

This happens because what you have there is not pattern matching, which is what case of is doing. If I am not mistaken, you are only allowed to have data type constructors in there and not actual functions.

If you tried something like

count a (b:xs) = c + count a xs
  where c = case b == a of
      True -> 1
      False -> 0

it would work, but then you are better off using if b == a then 1 else 0 instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top