scala传递类型参数函数作为另一个函数的参数 [英] scala pass type parameter function as a parameter of another function
问题描述
假设,我有一个函数,取两个值和一个函数作为参数。
def ls [S](a :S,b:S)(隐式evl:S => Ordered [S]):Boolean = a< (f(a,b))b
def myfunction [T](a:T,b:T,f:(T,T)=>布尔)= {
{
println(ok)
}
else {
println(not ok)
}
}
myfunction(1,2,ls)
IDE不会提供任何错误讯息,但当我尝试编译并运行时,compliter会发出以下消息:
错误:(14,19)没有隐式视图可用S =>序[S]。
myfunction(1,2,ls);}
^
有没有一种方法可以将类型参数函数作为另一个函数的参数传递?
b
$ b
myfunction [Int](1,2,ls)
myfunction(1,2,ls [Int])
从我的理解中,Scala编译器试图解析
找到第一个和第二个参数并很乐意将它分配给 Int
(或其超类型的任何东西)作为最佳匹配。
但第三个参数表示它可以获取任何参数!然后Scala编译器必须遵守并决定 T
将会是 Any
。这导致 S
的类型为任何
,并且没有隐式视图 Any => Ordered [Any]
您不能将 myfunction
定义为 ls
,而是 ls
可以定义 T
的类型。
这就是为什么这会起作用,因为你已经知道你想要什么类型的 f
了:
def myfunction [T](a:T,b:T)(f:(T,T)=>布尔)= {
...
}
myfunction(1,2)(ls)
Suppose,I have a function, take two values and a function as parameters.
def ls[S](a: S, b: S)(implicit evl: S => Ordered[S]): Boolean = a < b
def myfunction[T](a: T, b: T, f:(T,T)=>Boolean) = {
if (f(a, b)) {
println("is ok")
}
else {
println("not ok")
}
}
myfunction(1, 2, ls)
the IDE don't give any error message,but when I try to compile and run,the compliter give this message:
Error:(14, 19) No implicit view available from S => Ordered[S].
myfunction(1, 2, ls);}
^
So,is there a way to pass type parameter function as a parameter of another function ?
Firstly this works:
myfunction[Int](1, 2, ls)
myfunction(1, 2, ls[Int])
From my understanding the Scala compiler tries to resolve type T
of myfunction
.
It finds first and second argument and is happy to assign it to Int
(or anything that is its supertype) as the best match.
But the third argument says that it can get anything as a parameter! Then the Scala compiler must comply and decides that T
will be Any
. Which causes S
be of type Any
and there is no implicit view Any => Ordered[Any]
You must not think of myfunction
as defining a type for ls
but rather ls
defining what type T
can be.
Which is why this will work as you will already know what type of f
you want:
def myfunction[T](a: T, b: T)(f:(T,T)=>Boolean) = {
...
}
myfunction(1, 2)(ls)
这篇关于scala传递类型参数函数作为另一个函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!