Can you define your own operators in F#?

前端 未结 1 633
囚心锁ツ
囚心锁ツ 2020-12-16 14:34

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.

相关标签:
1条回答
  • 2020-12-16 15:09

    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 讨论(0)
提交回复
热议问题