Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell pattern matching a list of tuples

Tags:

haskell

As the post title says, I'm defining the following function in Haskell:

prop_LeftInverse :: (Eq a, Eq b) => [(a,b)] -> Bool
prop_LeftInverse (x,y):(xs,ys) = undefined

which should take as input a list of tuples. I'm getting a parse error in pattern but I can't quite figure out what it is, and also haven't found any information about this specific case...

like image 461
jl.lykon Avatar asked Nov 27 '13 19:11

jl.lykon


1 Answers

Almost right:

prop_leftInverse ((x, y):rest) = undefined

First of all, you need parentheses around the whole pattern. Second, the first element in the list is a tuple, but the rest of the list is just a list of tuples, not a tuple of lists.

If you look at simple pattern matching on a generic list

head :: [a] -> a
head [] = error "Empty list"
head (x:xs) = x

This works all values of type a, or all types. If you want a specific type, such as Int, you could do

headIsOne :: [Int] -> Bool
headIsOne (1:xs) = True
headIsOne _ = False  -- Here the _ matches anything

So, if you want to match a tuple:

addTup :: (Int, Int) -> Int
addTup (x, y) = x + y

we see that the pattern to match a tuple is exactly how we write one in code, so to match one at the beginning of list, we just have to match the first element with a specific pattern.

prop_leftInverse ((x, y):rest) = undefined

The rest of the list gets assigned to rest (although you can call it whatever you want).


Another example

If you wanted to grab the first two tuples:

myFunc ((x, y):(v, u):rest) = undefined

Or the first three:

myFunc ((x1, y1):(x2, y2):(x3, y3):rest) = undefined

By now I hope you can see the pattern (get it?)

like image 114
bheklilr Avatar answered Sep 22 '22 06:09

bheklilr