Haskell: where is the "parse error in pattern"

561 Views Asked by At

This is the code I have:

connected :: [(Integer,Integer)] -> Bool
connected [] = True
connected [(_,_)] = True
connected (a,b):(c,d):xs
                 | a > c     = False
                 |otherwise = connected (c,d):xs

When I load it GHCi it shows

error: parse error in pattern: connected

Where did I make a mistake?

1

There are 1 best solutions below

0
On

You need to add parentheses around your cons expressions in two places:

connected :: [(Integer,Integer)] -> Bool
connected [] = True
connected [(_,_)] = True
connected ((a,b):(c,d):xs)                           -- (2)
                 | a > c     = False
                 | otherwise = connected ((c,d):xs)  -- (1)
  1. Function application binds more tightly than infix operators, so connected (c,d) : xs gets parsed as (connected (c,d)) : xs.

  2. A similar thing happens in the pattern expression. Although the unhelpful error message you get there is rather unfortunate.

Opinionated side note: I recommend always writing infix operators with spaces around them (for example, a : b instead of a:b), because I think omitting the whitespace subtly implies that the operator binds more tightly than it really does.