当成员签名在F#中具有类型变量时成员约束调用表达式出现问题

时间:2015-04-09 18:19:37

标签: .net f# f#-3.0

当成员签名具有类型变量时,我在使用成员约束调用表达式时遇到了问题。具体来说,代码

[<AutoOpen>]
module Foo

// Preapplied lens
type lens <'i,'j> = { get : 'j; set : 'j -> 'i }

// Record type with lenses 
type foo1 = {
    num_ : int;
    letter_ : char
} with
    member this.num = {
        get = this.num_;
        set = (fun num' -> {this with num_=num'})}
    member this.letter = {
        get = this.letter_;
        set = (fun letter' -> {this with letter_=letter'})}
end

let (foo1:foo1) = {num_ = 1; letter_ = 'a'}

// Another ecord type with lenses 
type foo2 = {
    num_ : int;
    name_ : string
} with
    member this.num = {
        get = this.num_;
        set = (fun num' -> {this with num_=num'})}
    member this.name = {
        get = this.name_;
        set = (fun name' -> {this with name_=name'})}
end

let (foo2:foo2) = {num_ = 2; name_ = "bob"}

// Add two to any record with the num lens
let inline add2 (x : ^t) =
    let num = (^t : (member num : lens<^t,int>) (x)) in
    num.get + 2

给出错误:

  

test05.fsx(39,47):错误FS0010:表达式中的意外符号)

问题出在第二行到最后一行的成员约束调用表达式。基本上,我无法弄清楚如何在成员约束调用表达式中将类型变量^tint传递给lens类型。有没有一个很好的方法来实现这个目标?

1 个答案:

答案 0 :(得分:3)

静态约束中<^之间必须有空格:

// Add two to any record with the num lens
let inline add2 (x : ^t) =
    let num = (^t : (member num : lens< ^t,int>) (x)) in
    num.get + 2

否则,两个字符<^都将被视为中缀函数的名称(又名&#34;运算符&#34;)。