Domanda

This is an easy one (basic Scala syntax question). Assume I have a curried function that uses a parameterized type for its return value:

def elapsedNanos[R](repetitions: Int)(functionToTime: => R): Tuple2[R, Long] = {
  val start = System.nanoTime()
  for (i <- 1 until repetitions) {
    functionToTime
  }
  (functionToTime, System.nanoTime() - start)
}

I want to reference it by fixing the first parameter list. As shown below, I can obviously re-delare the type parameter and pass it on, by I was wondering if the code can become even less verbose using a placeholder:

// this works:
def execOnceElapsedNanos[R](functionToTime: => R) = 
   elapsedNanos(1)(functionToTime)

// this does not work:
def execOnceElapsedNanos = elapsedNanos(1)_

In the second case, when using a placeholder, the parametarization (? excuse my English, not a native speaker) is lost:

val (f: Long, elapsed: Long) = elapsedNanos {
  fibonacci(50)
}

Is there a syntax for such a case (i.e. placeholder that preserves type params) or is it simply not supported by the language?

È stato utile?

Soluzione

You can read blog series of blog post do get deep understanding why it happens: http://www.chuusai.com/2012/04/27/shapeless-polymorphic-function-values-1/.

As a simple workaround I would use something like this:

  def oneRep[T] = new ((T) => (T, Long)) {
    def apply(v1: T): (T, Long) = elapsedNanos(1)(v1)
  }

  println(oneRep(2+2))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top