Multiplying a list of tuples by a tuple in F#

风格不统一 提交于 2019-12-23 18:10:24

问题


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,

  • I have some tuple (a,b)
  • And some list of tuples [(c,d),(e,f),(g,h)...]
  • and I'm trying to get [(a*c,b*d),(a*e,b*f),(a*g,b*h)...]
  • and I'm trying to get (with a separate function) [(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


回答1:


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:

  • try to figure out the signature (well use F#/F# Interactive if you like)
  • maybe try to write a function where the parts of the tuple can have different types (hint: you need more than one op function)
  • why do you need more than one function for the last one? (why will withTuple (2.0,1) (*) [(2.1,3);(4.2,5)] not work - isn't (+) supposed to work for all numbers?)


来源:https://stackoverflow.com/questions/35397837/multiplying-a-list-of-tuples-by-a-tuple-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!