3

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?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Jack
  • 31
  • 1
  • Minor style note: `foo | x = False | otherwise = something` is (IMO) more commonly written as `foo = not x && something`. In your case, you can use `connected (...) = a <= c && connected (...)`. – chi Sep 06 '17 at 06:48

1 Answers1

6

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.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137