Created
January 31, 2019 18:05
-
-
Save kmizu/9e8a32e86e7d84582540e5aaef6e7065 to your computer and use it in GitHub Desktop.
Partial tail-recursion is also optimized in scalac. It's an experiment for verifying the result of https://twitter.com/chrilves/status/1091032475801927680
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>scalac PTailRecursion.scala | |
>javap -c PTailRecursion$ | |
Compiled from "PTailRecursion.scala" | |
public final class PTailRecursion$ { | |
public static PTailRecursion$ MODULE$; | |
public static {}; | |
Code: | |
0: new #2 // class PTailRecursion$ | |
3: invokespecial #12 // Method "<init>":()V | |
6: return | |
public int test(int); | |
Code: | |
0: iload_1 | |
1: iconst_0 | |
2: if_icmpne 10 | |
5: iload_1 | |
6: istore_1 | |
7: goto 0 | |
10: iconst_2 | |
11: aload_0 | |
12: iload_1 | |
13: invokevirtual #17 // Method test:(I)I | |
16: imul | |
17: ireturn | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>scalac PTailRecursion2.scala | |
PTailRecursion2.scala:7: error: could not optimize @tailrec annotated method test: it contains a recursive call not in tail position | |
2 * test(n) | |
^ | |
one error found |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object PTailRecursion { | |
def test(n: Int): Int = | |
if (n == 0) | |
test(n) | |
else | |
2 * test(n) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object PTailRecursion2 { | |
@annotation.tailrec | |
def test(n: Int): Int = | |
if (n == 0) | |
test(n) | |
else | |
2 * test(n) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment