Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In F#, is it possible to implement operators for tuples?

Tags:

f#

I am working with an API that represents points like float * float.

These are inconvenient to do arithmetic on:

let a = (3.0, 4.0)
let b = (2.0, 1.0)

let c = (fst a + fst b, snd a + snd b)

I would like to write:

let c = a + b

I can do this if I define my own type:

type Vector2 =
  {
    X : float;
    Y : float;
  }
  with
    static member (+) (a : Vector2, b : Vector2) =
      { X = a.X + b.X; Y = a.Y + b.Y }

But then I need to convert for the API I am using:

let c = a + b
let cAsTuple = (c.X, c.Y)

Alternatively, I could create a free function:

let add (ax, ay) (bx, by) = 
  (ax + bx, ay + by)

let c = a |> add b

But this is not quite as nice as true infix operators.

Does F# allow me to define custom operators for tuples?

like image 703
sdgfsdh Avatar asked Dec 06 '22 10:12

sdgfsdh


1 Answers

If you are willing to use a different operator like (+.) you can do this:

let inline (+.) (a,b) (c,d) = (a + c, b + d)

it works with ints, floats, strings:

( 4 ,  3 ) +. ( 3 ,  2 ) // (7, 5)
( 4.,  3.) +. ( 3.,  2.) // (7.0, 5.0)
("4", "3") +. ("3", "2") // ("43", "32")
like image 76
AMieres Avatar answered Jan 12 '23 22:01

AMieres