开发者

Can you define your own operators in 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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜