Home > OS >  Adding two tuples of floats
Adding two tuples of floats

Time:10-10

I need to make a function that adds two tuples consisting of floats, and returns a tuple of two floats.

let add a b =
  fst a   fst b, snd a   snd b

Gives me this return:

val add : int * int -> int * int -> int * int

But if I try with:

let add (a:float) (b:float) =
  fst a   fst b, snd a   snd b

I get this:

This expression was expected to have type
    ''a * 'd'    
but here has type
    'float'    

How do I go about getting the following return?

val add : float * float -> float * float -> float * float

CodePudding user response:

If you want both a and b to be of type float * float, you can just straight up specify that:

let add (a : float * float) (b : float * float) = ...

Or you can destructure the tuples right in the parameter declarations:

let add (a1:float, a2:float) (b1:float, b2:float) =
    (a1   b1), (a2   b2)

Incidentally, you only have to specify type of one of the tuples, the other one will be inferred from the fact that it's elements are added to those of the first tuple:

let add (a1:float, a2:float) (b1, b2) =
    (a1   b1), (a2   b2)

Alternatively, you can mark the function inline:

let inline add a b = ...

This will mean that the function doesn't get compiled into IL, but instead gets expanded at every use site. This, in turn, will make it able to work with any type that has the operator.

A function compiled to IL cannot do that, because IL does not allow to specify a constraint like "has a operator". But the compiler has to use some type, so it defaults to int.


Even more alternatively, you can prevent the compiler from defaulting to int by giving it some other source to infer the types from. For example, a use site in the same file:

let add a b = ...

let x = add (1.0, 2.0) (3.0, 4.0)

The last line will let the compiler know that you expect the parameters to be float.

CodePudding user response:

If you know the tuples will always contain floats, I think the cleanest way is like this:

let add (ax : float, ay : float) (bx : float, by : float) =
    (ax   bx), (ay   by)
  • Related