2

Typing the following into a GHC interpreter

let describe' all@([x] ++ [y]) = "The first letter of " ++ all ++ " is " ++ [x]

yields

Parser error in pattern: [x] ++ [y]

Why is Haskell unable to match the pattern all@([x] ++ [y]) against expressions like "HI" or [1,2]?

4
  • Basically he cant know what is the length of the list and ++ is actually a function so you cant pattern match against it, Haskell pattermatch constructors for example. Commented Mar 29, 2016 at 16:00
  • maybe because it's ambiguously? Commented Mar 29, 2016 at 16:00
  • So haskell doesn't see [x] + [y], it sees the return value of ++ which in this case is a list of ambiguous size? Commented Mar 29, 2016 at 16:03
  • 2
    no it just sees the function ((++)) and will stop right there with an syntax-error - just as in your other question Commented Mar 29, 2016 at 16:04

2 Answers 2

9

let's assume you could pattern-match on ++ - now think about how you could match this:

a ++ b = [1,2]

you could have:

  • a = [1,2], b = []
  • a = [1], b = [2]
  • a = [], b = [1,2]

now what is the right one?


the technical reason is that ++ is not data-constructor ;)


in your specific situation you could use

let describe' all@[x,y] = "The first letter of " ++ all ++ " is " ++ [x]

(which will only match strings with length exactly 2)

or better

let describe' all@(x:_) = "The first letter of " ++ all ++ " is " ++ [x]

(which will match all strings of length at least 1)

a safe version would be this

describe' :: String -> String
describe' ""        = "your input was empty"
describe' all@(x:_) = "The first letter of " ++ all ++ " is " ++ [x]
Sign up to request clarification or add additional context in comments.

3 Comments

Indeed! If pattern matching were that magic, I would try something like let foo (isProofOfPneqNP s) = "Eureka! " ++ s in foo True ;-))
I think this is what the mice build earth for ;)
... or Curry (only to say that such constructs are possible in principle).
6

You may only use constructors in pattern matches. The pattern [x] desugars to the pattern x:[], where : and [] are both constructors. ++, however, is a function. This is a small flaw of the Haskell language design in that we are unable to quickly distinguish between what symbols we have defined as functions and what symbols come to us from their datatype declarations. For a full treatment, see section 3 of the Haskell 2010 Language Report.

1 Comment

Although, an infix constructor must start with :, so you can at least identify which functions are not constructors. So ++ is definitely not a constructor, while something like :+ might be a constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.