Reputation: 89
I'm writing some code in F# and I need to multiply and add each element in list of tuples (c,d)
by a tuple (a,b)
.
To clarify,
(a,b)
[(c,d),(e,f),(g,h)...]
[(a*c,b*d),(a*e,b*f),(a*g,b*h)...]
[(a+c,b+d),...]
I have tried to use List.map
to multiply each element in the list by a tuple but I get an error that *
is an invalid operator for type tuple.
This is how I ended up implementing the multiplication function recursively with pattern matching:
let rec mtp(t:term,p:poly):poly =
match (t, p) with
| (a,b),[] -> []
| (a, b),(c,d)::ps -> (a*c,b*d)::mtp(t,ps)
Where term is a tuple of float * int and poly is a list of terms
Upvotes: 3
Views: 940
Reputation: 52300
Ok List.map
is a good idea - you only have to make sure that you provide something (let's say a lambda) to tell F# how to operate on two tuples.
To make it a bit more general you could do something like this:
let withTuple (a,b) op tpls =
List.map (fun (a',b') -> (op a a', op b b')) tpls
And work with it as you expected
> withTuple (1,1) (+) [(2,3);(4,5)];;
val it : (int * int) list = [(3, 4); (5, 6)]
> withTuple (2,1) (*) [(2,3);(4,5)];;
val it : (int * int) list = [(4, 3); (8, 5)]
to understand it a bit better you should:
op
function)withTuple (2.0,1) (*) [(2.1,3);(4.2,5)]
not work - isn't (+)
supposed to work for all numbers?)Upvotes: 6