Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "(_:_:_)" mean in Haskell (non-exhaustive pattern matching error from GHCI)?

I'm getting the following error from GHCI when I run my Haskell program:

"Pattern match(es) are non-exhaustive
 In an equation for `recaList': Patterns not matched: (_:_:_)"

I've been searching the web/SO, but can't seem to find an explanation for what (_:_:_) is. My guess would be just an empty list, but I've accounted for that in my function.

Not sure if it's relevant, but here's my program:

recaList :: [Int] -> [Int]
recaList [] = []
recaList [x] = map recaMan [x]

I think the issue is just that I have no idea what (_:_:_) is.

like image 509
Caroline Avatar asked Dec 17 '22 18:12

Caroline


1 Answers

recaList :: [Int] -> [Int]
recaList [] = []
recaList [x] = map recaMan [x]

This is matching empty lists and lists containing one element. You have failed to match any list containing two or more elements. I believe what you meant was

recaList :: [Int] -> [Int]
recaList [] = []
recaList xs = map recaMan xs

No need for the brackets. However, map will return the empty list if given it as input, so your first case is also unnecessary. Although the above snippet will work, this would be more idiomatic.

recaList :: [Int] -> [Int]
recaList xs = map recaMan xs

As to your question about what the error syntax means, : is the list construction operator, so (x:xs) matches any nonempty list, binding the first element to x and the rest to xs. (x:y:ys) does the same, but it binds the first to x, the second to y, and the remainder to ys. An underscore simply indicates an ignored value, so (_:_:_) matches any list of at least two elements. The compiler is telling you that you failed to match this case.

like image 129
Silvio Mayolo Avatar answered Dec 20 '22 08:12

Silvio Mayolo