有没有办法为F#构造函数中的函数指定命名参数?

时间:2016-03-22 21:54:32

标签: f#

有没有办法在构造函数中命名函数参数?

type UnnamedInCtor(foo: string -> string -> bool) = 
    member this.Foo: string -> string -> bool = foo
    member this.Bar: a:string -> b:string -> bool = foo
    member this.Fizz = foo

//Does not compile
type NamedInCtor(foo: a:string -> b:string -> bool) = 
    member this.Foo: string -> string -> bool = foo
    member this.Bar: a:string -> b:string -> bool = foo
    member this.Fizz = foo

2 个答案:

答案 0 :(得分:1)

您需要在构造函数中解压缩该函数:

type NamedInCtor(a, b) = 
    member this.Foo: string -> string -> bool = a b
    member this.Bar: string -> string -> bool = a b
    member this.Fizz = a b

请注意,此处隐式输入a和b。您应该信任编译器尽可能地执行此操作,因为它使您的代码更具可读性。

请记住,函数是第一类类型,不鼓励使用传统对象。你问的基本上是“我可以命名并访问这种类型的任意子集吗?”答案是否定的。如果你想要那种行为,那么你必须构建你的函数来请求它。

答案 1 :(得分:1)

我认为在F#中这是不可能的,但是如果你想记录foo所代表的内容,你可以使用type abbreviations

// Compiles
type aToBToC = string -> string -> bool
type NamedInCtor(foo: aToBToC) = 
    member this.Foo: string -> string -> bool = foo
    member this.Bar: a:string -> b:string -> bool = foo
    member this.Fizz = foo
相关问题