scala - Evaluating intermediate function values only once -


i need function translate , scale complex number, i.e if z complex, fuction should return ( z - translate ) * scale function parametrized dimensions of screen , scaling factor, here have:

def afftransform(width: int, height: int, scalefactor: double)(z: complex): complex = {     val scale: double = 4.0 / width     val translate = complex(width / 2, height / 2)     (z - translate) * scale } 

with in place, following works expected:

val transform: complex => complex = afftransform(w, h, 4)     ... val zz: complex = transform(z) 

the problem calculation:

    val scale: double = 4.0 / width     val translate = complex(width / 2, height / 2) 

is performed every time transform applied conceptually redundant. case when afftransform not curried , transform defined partially applied.

is there way define afftransform and\or transform scale , translate calculated once?

simply take away last of argument lists , return function instead:

case class complex(re: double, im: double) {   def - (that: complex) = complex(this.re - that.re, this.im - that.im)   def * (scalar: double) = complex(re * scalar, im * scalar) }  def aff(width: int, height: int, scalefactor: double): complex => complex = {   println("heavy calculation here...")   val scale: double = 4.0 / width   val translate = complex(width / 2, height / 2)   z: complex => (z - translate) * scale }  val transform: complex => complex = aff(640, 480, 4) transform(complex(12, 34)) 

Comments