当成员签名在 F# 中具有类型变量时,成员约束调用表达式出现问题
Trouble with a member constraint invocation expression when the member signature has type variables in F#
当成员签名具有类型变量时,我在使用成员约束调用表达式时遇到问题。具体来说,代码
[<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): error FS0010: Unexpected symbol )
in expression
问题出在倒数第二行的成员约束调用表达式中。基本上,我不知道如何将类型变量 ^t
和 int
传递给成员约束调用表达式中的 lens
类型。有什么好的方法可以实现吗?
静态约束中<
和^
之间必须有一个space:
// 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
否则,两个字符 <^
将被视为中缀函数的名称(又名 "operator")。
当成员签名具有类型变量时,我在使用成员约束调用表达式时遇到问题。具体来说,代码
[<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): error FS0010: Unexpected symbol
)
in expression
问题出在倒数第二行的成员约束调用表达式中。基本上,我不知道如何将类型变量 ^t
和 int
传递给成员约束调用表达式中的 lens
类型。有什么好的方法可以实现吗?
静态约束中<
和^
之间必须有一个space:
// 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
否则,两个字符 <^
将被视为中缀函数的名称(又名 "operator")。