函数的类型推断作为参数 [英] Type inference of functions as arguments
问题描述
我想编写一个函数,该函数将几个tupple作为参数,并选择它们的第ith个元素,然后传递给另一个函数,其中i作为另一个参数给出.我已经尝试过这样的事情:
I would like to write a function which takes several tupples as arguments and choose theirs ith elements and passes to another function, where i is given as another argument. I've tried sth like this:
let function (tup1:'A*'A) (tup2:'B*'B) i =
otherFunction (i tup1) (i tup2)
function Tup1 Tup2 fst
我遇到了一个错误,因为预期i
应该是'A*'A ->'A
而不是'B*'B->'B
.
有什么办法可以使此代码正常工作?
I've got an error, because i
was expected to be 'A*'A ->'A
not 'B*'B->'B
.
Is it any way to make this code to work?
谢谢.
推荐答案
您基本上想传递类型为∀'a.'a*'a->'a
的参数,但是在F#(和其他ML)中,只有
You basically want to pass an argument of type ∀'a.'a*'a->'a
, but in F# (and other MLs), only rank-1 polymorphism is supported so you can't do this directly. The workaround is to define a new type with a generic method to emulate higher-rank polymorphism:
type Untupler =
abstract Apply : 'a*'a -> 'a
let myFunction tup1 tup2 (i:Untupler) =
otherFunction (i.Apply tup1) (i.Apply tup2)
myFunction Tup1 Tup2 { new Untupler with member __.Apply (x,y) = x }
这篇关于函数的类型推断作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!