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

查看:21
本文介绍了你能在 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]

可以在 F# 运算符中使用的字符在 文档.它们是 !%&*+-./<=>@^|~ 并且对于第一个之后的任何字符,?.优先级和固定性由运算符的第一个字符决定(参见规范).

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).

您可以像我上面所做的那样创建自己的 let-bound 运算符,在这种情况下,它们就像 let-bound 函数一样工作.您还可以将它们定义为类型的成员:

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)

在这种情况下,您不需要预先定义一个 let-bound 函数来使用运算符;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天全站免登陆