通用scala函数,其输入是变量arity的函数 [英] Generic scala function whose input is a function of variable arity
问题描述
我想定义一个函数 f
,它需要另一个函数 g
。我们要求 g
取 n
)并返回一个Double。函数调用 f(g)
应返回特定值 n
。
$例如,因为Math.sin的类型为
(Double,Double)=>,所以 f(Math.max)= 2
Double 和 f(Math.sin)= 1
,因为Math.sin的类型为 Double => Double 。
如何使用Scala泛型定义 f
?
我尝试了几种不成功的表单。例如:
def f [A< ;: Product](g:Product => Double)= {... }
这是行不通的,因为我们无法提取 n
,并且不能限制 A
只包含 Double
值。
解决方案有一种模式叫做 Spray 团队创建的磁铁模式/>磁铁模式。它确实是你想要的东西
I want to define a function f
that takes another function g
. We require g
to take take n
Doubles (for some fixed n
) and return a Double. The function call f(g)
should return the specific value of n
.
For example, f(Math.max) = 2
since Math.sin has type (Double, Double) => Double
, and f(Math.sin) = 1
since Math.sin has type Double => Double
.
How can I define f
using Scala generics?
I've tried several forms without success. For example:
def f[A <: Product](g: Product => Double) = {...}
This doesn't work since we cannot extract the value of n
at compile time, and cannot constrain the A
to contain only Double
values.
解决方案 There is a pattern called Magnet Pattern, created by the Spray team. It does exectly what you want
这篇关于通用scala函数,其输入是变量arity的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!