Tail recursiveness in Scala methods with multiple parameter lists -
i have next function:
@tailrec def sameprefix[a](length: int)(a: vector[a], b: vector[a]): boolean = { if(length<1) true else{ if(a(length-1)==b(length-1)) sameprefix(length-1)(a, b) else false } }
which checks if 2 vectors have equal first elements, given length check.
i wondering if part calls
sameprefix(length-1)(a, b)
would first create function object sameprefix(length-1)
, apply (a,b)
it, or if phone call method tail-recursively.
let's see...
$ scala welcome scala version 2.11.1 type in expressions have them evaluated. type :help more information. scala> import scala.annotation._ import scala.annotation._ scala> @tailrec def curried(a: int)(b: int): int = curried(a-1)(b-1) curried: (a: int)(b: int)int scala> :javap curried ... irrelevant output removed ... public int curried(int, int); flags: acc_public code: stack=3, locals=3, args_size=3 0: iload_1 1: iconst_1 2: isub 3: iload_2 4: iconst_1 5: isub 6: istore_2 7: istore_1 8: goto 0 ... irrelevant output removed ...
as can see, there no recursive invocation in bytecode. instead, there goto 0
instruction indicates loop. means tail phone call optimization has taken place.
you'll notice multiple parameter lists have been squashed single parameter list in compiled bytecode, there no intermediate functions involved.
edit: actually, didn't have inspect bytecode 100% sure method has been compiled tco, because @tailrec
annotation exists purpose. in other words, if set @tailrec
on method , compiles without errors, can 100% sure has been compiled tco.
scala
No comments:
Post a Comment