JJ chips
JJ chips

Reputation: 97

What is the (_:xs) notation in haskell?

I see the function

last_element :: [a] -> a
last_element (_:xs)= last_element xs

I don't understand the underscore colon in "(_:xs)". I read that it seperates the head from the list inputted. Is the underscore colon just removing the first digit, or the "head", of the list in a primitive recursive way?

edit, from my understanding, this function would lack a base case. Is this right?

Upvotes: 2

Views: 1815

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

The underscore allows you to pattern match but implies that you will not actually be using the value. Your pattern matching is not exhaustive, so it won't actually work. You'll need to define the missing patterns to fix it:

last_element :: [a] -> a
last_element [] = error "Empty List"
last_element [x] = x
last_element (_:xs)= last_element xs

Upvotes: 2

Related Questions