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...
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?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With