您可以在F#中定义自己的运算符吗? [英] Can you define your own operators in F#?

查看:80
本文介绍了您可以在F#中定义自己的运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在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.

推荐答案

是:

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)

在这种情况下,您不需要预先定义一个让函数绑定的函数即可使用该运算符. F#会在类型上找到它.您可以使用内联定义特别好地利用此优势:

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

这篇关于您可以在F#中定义自己的运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆