beardc
beardc

Reputation: 21063

Pattern match on a list of tuples

If I want to add all the elements of a list of tuples, I get an error with the following

let rec addTupLst (xs: 'a * 'a list) =
    match xs with
    | (a, b) :: rst -> a + b + (addTupLst rst)
    | _ -> 0

addTupLst [(1, 2)]

I get the warning

error FS0001: This expression was expected to have type
'a * 'a list
but here has type
'b list

Is it not possible to pattern match on a list of tuples this way, or is there another error?

Upvotes: 4

Views: 1053

Answers (2)

Tarmil
Tarmil

Reputation: 11362

The problem is that you declare the function as taking a 'a * 'a list, but what you actually want to write is ('a * 'a) list.

This is one of the reasons why I don't really like the common but (IMO) inconsistent style of using prefix notation for type parameters for some built-in types and postfix notation for the rest. I prefer to write the type as list<'a * 'a>.

Upvotes: 2

robkuz
robkuz

Reputation: 9914

You just forgot a pair of parens

let rec addTupLst (xs: ('a * 'a) list) =
     match xs with
     | (a, b) :: rst -> a + b + (addTupLst rst)
     | _ -> 0

addTupLst [(1, 2)]

Upvotes: 3

Related Questions