我正在调查 aether library并注意到了这一点
type Lens<'a,'b> =
('a -> 'b) * ('b -> 'a -> 'a)
static member (^=) (Set, (_, s): Lens<'a,'b>) =
fun (b: 'b) ->
s b : 'a -> 'a
在 ^= 函数中,b 参数 if 是 lambda 中的 'b 类型。但是,在lamda体内,为什么b类型现在是'a?
最佳答案
However, in the lamda body, why is b type of 'a now?
不是。
b
是输入 'b
,如fun (b: 'b) ->
所示.
我们可以在没有匹配项的情况下重写该成员,并使用本地定义的函数,如下所示:
static member (^=) (Set, lens: Lens<'a,'b>) =
// Pattern match to extract out the 2nd portion of the lens, which is a function: 'b -> 'a -> 'a
let (_,s) = lens
// Define a function that takes a 'b and returns a new function of type: 'a -> 'a
let fn (b: 'b) : 'a -> 'a =
s b // this just partially applies s with the input "b"
fn // Return the function
基本上,(Set, (_,s))
在参数列表中将“s”绑定(bind)到 Lens<'a,'b>
的第二部分, 或类型为 ('b -> 'a -> 'a)
的函数.上面,我已经把它分解得更明确,并在它自己的绑定(bind)中完成了这个提取。
然后该成员返回一个本地定义的函数(作为 lambda)。在上面,我使用 let 绑定(bind)函数重写了它,因为它通常更清晰。
关于f# - 为什么这个例子中参数 b 的类型是 a?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45110111/