PinkiePie-Z
PinkiePie-Z

Reputation: 553

How to do pattern matching with tuple in Haskell?

I have a problem when trying to type match with tuple.

filterSth :: [a]->[b]->([a],[b])
filterSth _ [] = (_, [])

It means that when the second argument is an empty list, I don't care the first element of the tuple that I wish to return. How can I implement this ?

Upvotes: 1

Views: 608

Answers (2)

Jan
Jan

Reputation: 11726

If you don't care about the first element of the tuple and you're sure you won't use it you can return undefined, i.e.

filterSth _ [] = (undefined, [])

Remember that trying to evaluate undefined will result in a runtime exception.

Another idea might be to return Either ([a], [b]) [b] instead.

filterSth :: [a] -> [b] -> Either ([a], [b]) [b]
filterSth _ [] = Right []
-- and a case for a non-empty second argument

If you want to return the first argument unchanged you cannot use _. _ means that you don't care what's the value of the argument and you're not going to use it. Since you are going to use it you have to replace _ with a named argument and explicitly return it

filterSth a [] = (a, [])

Upvotes: 7

augustss
augustss

Reputation: 23014

If you don't care what you return as the first component of the tuple, I suggest you return an error that will blow up if you accidentally use it.

filterSth _ [] = (error "Don't use this", [])

Upvotes: 5

Related Questions