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?

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 (...). Commented Sep 6, 2017 at 6:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.