Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you define your own operators in F#?

Tags:

operators

f#

Is there a way to define your own operators in F#?

If so can someone give me an example for this? I searched briefly, but couldn't find anything.

like image 634
Joan Venge Avatar asked Feb 05 '10 22:02

Joan Venge


1 Answers

Yes:

let (+.) x s = [for y in s -> x + y]
let s = 1 +. [2;3;4]

The characters that can be used in an F# operator are listed in the docs. They are !%&*+-./<=>@^|~ and for any character after the first, ?. Precedence and fixity are determined by the first character of the operator (see the spec).

You can create your own let-bound operators as I've done above, in which case they work just like let-bound functions. You can also define them as members on a type:

type 'a Wrapper = Wrapper of 'a with
  static member (+!)(Wrapper(x), Wrapper(y)) = Wrapper(x+y)

let w = (Wrapper 1) +! (Wrapper 2)

In this case, you don't need to have pre-defined a let-bound function to use the operator; F# will find it on the type. You can take particularly good advantage of this using inline definitions:

let inline addSpecial a b = a +! b
let w2 = addSpecial w (Wrapper 3)

Taking this even further, you can make the operators on your types inline as well, so that you can use them on an even wider variety of instances of your class:

type 'a Wrapper = Wrapper of 'a with
  static member inline (+!)(Wrapper(x), Wrapper(y)) = Wrapper(x+y)

let wi = (Wrapper 1) +! (Wrapper 2)
let wf = (Wrapper 1.0) +! (Wrapper 2.0)
let wi2 = addSpecial wi wi
let wf2 = addSpecial wf wf
like image 115
kvb Avatar answered Oct 17 '22 20:10

kvb