使用元组对抽象类型进行类型推断 [英] type inference on abstract type with a tuple
问题描述
基于此 kvb的答案,此代码进行了编译(F#4 )并运行:
Based on this kvb's answer, this code compiles (F#4) and runs :
type Untupler = abstract Apply : 'u * 'u -> 'u
let myotherFun arg1 arg2 =
printfn "myotherFun result is : %A %A" arg1 arg2
let myFunction tup1 tup2 (i:Untupler) =
myotherFun (i.Apply tup1) (i.Apply tup2)
let reskvb = myFunction (1,2) ("Hello","World") { new Untupler with member __.Apply (x,y) = snd (x,y) }
但是如果最后一行替换为初始答案:
But if the last line is replaced by the initial answer :
let reskvb = myFunction (1,2) ("Hello","World") { new Untupler with member __.Apply x = fst x }
然后,编译器抱怨FS0768错误: 成员"Apply"不接受正确数量的参数,预计需要2个参数
then the compiler complains with error FS0768 : The member 'Apply' does not accept the correct number of arguments, 2 arguments are expected
我不明白为什么编译器似乎无法推断x确实是一个元组.还是我还缺少另一个问题?谢谢.
I do not understand why the compiler seems to fail to infer that x is indeed a tuple. Or is there another issue I am missing ? Thx.
推荐答案
这样做的原因是,当您开始使用接口时,您会进入F#对面向对象编程的支持,而在F#中,所有 OOP互操作方法默认为元组.
The reason for this is that when you start using interfaces, you move into F#'s support for Object-Oriented Programming, and in F#, all OOP interop methods are tupled by default.
因此,Apply
方法被解释为带有两个方法参数的方法,而不是一个带有单个元组作为输入的函数.
Thus, the Apply
method is interpreted as being a method that takes two method arguments, rather than a function that takes a single tuple as input.
这篇关于使用元组对抽象类型进行类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!