对无限参数应用功能 [英] Apply function on unlimited parameters
问题描述
我想写一个函数,可以通过这个语法获得无限的参数。
myfunc arg1 arg2 arg3 ....
我尝试了一些使用curring,但没有任何帮助
i试图使其递归,但后来scala编译器说:
scala递归方法需要结果类型
递归:
def func(x:Int)= {
doSomething(x); myVal:Int => func(myVal)
}
感谢帮助者
所以你寻找的函数需要一个特定类型的参数,并且必须返回一个函数,该函数接受一个相同类型的参数并返回一个函数使用相同类型的参数等等,ad infinitum。
这个问题的类型是这样的: p>
T [X] = X => T [X]
也就是说,它是一个递归的自引用类型。因为它是自引用的,所以我们必须将其命名为在其内部重用它的唯一目的(不幸的是,Scala没有用于无限类型的定点组合器)。我们称之为 InfCurry
,它看起来像这样:
trait InfCurry [T] extends(T => InfCurry [T])
正如您所看到的,它模仿上面的定义非常好(另一种选择应该是类型别名,但Scala不支持递归类型别名)。
让我们定义一个构造函数方法来帮助使用定义我们无限的curry函数:
object InfCurry {
def apply [T](f:T => InfCurry [T]):InfCurry [T] = new InfCurry [T] {
def apply(x:T)= f(x)
}
}
$ c
$ b 使用这个小工具,你可以定义这样的东西:
val f:InfCurry [Int] = InfCurry {x =>
println(x)
f
}
这个小东西是这样的:
pre $ code> val g = f(1)(2)(3)(4)(5)( 6)(7)
g(8)(9)(10)(11)(12)
可能在这种情况下,您希望使用可变数量参数的方法 - 请参阅其他答案 - 但这是您要求的。
I would like to write a function that can get unlimited parameters with this syntax
myfunc arg1 arg2 arg3 .... I have tried some using curring but nothing helped i have tried to make it recursivly but then scala compiler says: "scala recursive method needs result type" Recursive :
def func(x:Int) = {
doSomething(x); myVal:Int=>func(myVal)
}
thanks for helpers
So the function you seek takes an argument of a certain type and must return a function which takes an argument of the same type and returns a function with takes an argument of the same type and so on, ad infinitum.
The problem here is that the type of this function is something on the lines of:
T[X] = X => T[X]
That is, it is a recursive, self-referencing type. Because it is self referencing we must name it for the sole purpose of reusing it within itself (Unfortunately, Scala has no fixed-point combinator for infinite types). Let's call it InfCurry
and it looks something like this:
trait InfCurry[T] extends (T => InfCurry[T])
As you can see, it mimics the above definition quite well (another option would have been type aliases, but Scala doesn't support recursive type-aliases).
Let's also define a constructor method to help use define our infinitely curried functions:
object InfCurry {
def apply[T](f: T => InfCurry[T]): InfCurry[T] = new InfCurry[T] {
def apply(x: T) = f(x)
}
}
With this little tool you can define stuff like this:
val f: InfCurry[Int] = InfCurry { x =>
println(x)
f
}
And you would use this little thing like this:
val g = f(1)(2)(3)(4)(5)(6)(7)
g(8)(9)(10)(11)(12)
Probably in this case you would like to use method with variable number of arguments - see the other answer - but this is what you asked.
这篇关于对无限参数应用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!