繁体   English   中英

使用F#在类/接口中动态定义几个成员

[英]Define several members dynamically in class/interface using F#

我正在使用F#进行小型程序开发,仅用于个人培训,但花了点时间,我无法解决。

我正在描述一些接口:

type IСalculations =
    abstract member Add : int * int -> int
    abstract member Subtract : int * int -> int
    abstract member Multiply : int * int -> int
    abstract member Divide : int * int -> int

如您所见,除名称外,成员签名是相同的。

我能否在下一个中使用F#(现在将是伪代码 ):

let names = [ "Add", "Subtract", "Multiply", "Divide" ];
let ICalculations = new interface;

foreach ( name in names ) {
    ICalculations[ name ] : int * int -> int
}

目的不是要为每个成员重复签名int * int -> int

可能吗?

接口声明后不能定义接口方法类型。 但是您可以定义例如Dictionary,其中包含您类型的函数:

open System.Collections.Generic    
type Ops = Add | Subtract | Multiply | Divide
let pseudoInterface = Dictionary<Ops, int * int -> int>()

// Then somewhere in your program you could define this "methods"
pseudoInterface.[Add] <- fun (i, j) -> i + j
pseudoInterface.[Subtract] <- fun (i, j) -> i - j // etc...

或者,为了简洁起见,您可以为函数类型定义类型别名:

type Op = int * int -> int
type IСalculations =
    abstract member Add : Op    
    abstract member Subtract : Op
    abstract member Multiply : Op
    abstract member Divide : Op

声明接口的唯一语法是:

// Interface declaration:
[ attributes ]
type interface-name =
   [ interface ]     [ inherit base-interface-name ...]
     abstract member1 : [ argument-types1 -> ] return-type1
     abstract member2 : [ argument-types2 -> ] return-type2
     ...
   [ end ]

在伪代码的第二行:

let ICalculations = new interface;

您希望使用let绑定或等效绑定。 不幸的是,让绑定仅将标识符与值或函数相关联,而不与类型或接口相关联。 因此,恐怕没有办法。 F#之外的其他功能语言(例如Idris)也可以做到。 如果您只被重复int * int-> int的冗长困扰,则可以定义类型别名,如下所示:

module T =
  type Op = int * int -> int

type IСalculations =
    abstract member Add : T.Op
    abstract member Subtract : T.Op
    abstract member Multiply : T.Op
    abstract member Divide : T.Op

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM