在varargs中使用惰性求值函数

时间:2010-04-11 22:07:47

标签: scala variadic-functions lazy-evaluation

以下方法有什么问题?

def someMethod(funcs: => Option[String]*) = {
 ...
}

2 个答案:

答案 0 :(得分:5)

如果添加parens,实际上“在2.7.7下工作”:

scala> def someMethod(funcs: => (Option[String]*)) = funcs
someMethod: (=> Option[String]*)Option[String]*

除了它在运行时实际上不起作用:

scala> someMethod(Some("Fish"),None)
    scala.MatchError: Some(Fish)
at scala.runtime.ScalaRunTime$.boxArray(ScalaRunTime.scala:136)
at .someMethod(<console>:4)
at .<init>(<console>:6)
at .<clinit>(<console>) ...

在2.8中,它拒绝让你指定X *作为任何函数或by-name参数的输出,即使你可以将它指定为输入(这是r21230,后Beta 1):

scala> var f: (Option[Int]*) => Int = _
f: (Option[Int]*) => Int = null

scala> var f: (Option[Int]*) => (Option[Int]*) = _
<console>:1: error: no * parameter type allowed here
       var f: (Option[Int]*) => (Option[Int]*) = _

但是如果你试图从一个方法转换它,它可以工作:

scala> def m(oi: Option[Int]*) = oi
m: (oi: Option[Int]*)Option[Int]*

scala> var f = (m _)
f: (Option[Int]*) => Option[Int]* = <function1>

scala> f(Some(1),None)
res0: Option[Int]* = WrappedArray(Some(1), None)

所以它并不完全一致。

在任何情况下,您都可以通过传入一个Array然后将该数组发送到需要重复参数的内容来实现您想要的目标:

scala> def aMethod(os: Option[String]*) { os.foreach(println) }
aMethod: (os: Option[String]*)Unit

scala> def someMethod(funcs: => Array[Option[String]]) { aMethod(funcs:_*) }
someMethod: (funcs: => Array[Option[String]])Unit

scala> someMethod(Array(Some("Hello"),Some("there"),None))
Some(Hello)
Some(there)
None

如果你真的想(轻松)传递一堆懒惰的评估参数,那么你需要一些基础设施,据我所知,在库中不存在很好(这是2.8的代码;查看它作为2.7)中类似策略的灵感来源:

class Lazy[+T](t: () => T, lt: Lazy[T]) {
  val params: List[() => T] = (if (lt eq null) Nil else t :: lt.params)
  def ~[S >: T](s: => S) = new Lazy[S](s _,this)
}
object Lz extends Lazy[Nothing](null,null) {
  implicit def lazy2params[T : Manifest](lz: Lazy[T]) = lz.params.reverse.toArray
}

现在,您可以轻松创建一系列懒惰评估的参数:

scala> import Lz._  // To get implicit def
import Lz._

scala> def lazyAdder(ff: Array[()=>Int]) = {
     |   println("I'm adding now!");
     |   (0 /: ff){(n,f) => n+f()}
     | }
lazyAdder: (ff: Array[() => Int])Int

scala> def yelp = { println("You evaluated me!"); 5 }
yelp: Int

scala> val a = 3
a: Int = 3

scala> var b = 7
b: Int = 7

scala> lazyAdder( Lz ~ yelp ~ (a+b) )
I'm adding now!
You evaluated me!
res0: Int = 15

scala> val plist = Lz ~ yelp ~ (a+b)
plist: Lazy[Int] = Lazy@1ee1775

scala> b = 1
b: Int = 1

scala> lazyAdder(plist)
I'm adding now!
You evaluated me!
res1: Int = 9

答案 1 :(得分:3)

显然,重复的参数不适用于名称参数。