Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `++` in pattern matching

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]?

like image 946
George Avatar asked Mar 15 '26 08:03

George


1 Answers

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]
like image 189
Random Dev Avatar answered Mar 17 '26 23:03

Random Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!