updated
authorChristian Urban <christian.urban@kcl.ac.uk>
Wed, 26 Nov 2025 21:32:41 +0000
changeset 1033 677a3572f453
parent 1032 1d3503a95a49
child 1034 94cf7cb122b3
updated
hws/hw08.pdf
hws/hw08.tex
Binary file hws/hw08.pdf has changed
--- a/hws/hw08.tex	Fri Nov 21 10:34:01 2025 +0000
+++ b/hws/hw08.tex	Wed Nov 26 21:32:41 2025 +0000
@@ -117,30 +117,29 @@
 \item The JVM method given below is code for the following recursive function
 
 \begin{lstlisting}[numbers=none]
-def add(x, y) = if x == 0 then y else add(x - 1, y + 1)
+def gcd(a, b) = if b == 0 then a else gcd(b, a \% b)
 \end{lstlisting}
 
-Rewrite the JVM code such that the recursive call at the end is removed.
+Rewrite the JVM code such that the recursive call at the end is replaced by a tailcall to the beginning.
 
 \begin{lstlisting}[language=JVMIS,numbers=none]
-.method public static add(II)I
+.method public static gcd(II)I
 .limit locals 2
-.limit stack 7
-  iload 0
-  ldc 0
-  if_icmpne If_else_4
-  iload 1
-  goto If_end_5
-If_else_4:
-  iload 0
-  ldc 1
-  isub
-  iload 1
-  ldc 1
-  iadd
-  invokestatic defs/defs/add(II)I  ;; recursive call
-If_end_5:
-  ireturn
+.limit stack 6
+gcd_Start:
+   iload 1
+   ldc 0
+   if_icmpne If_else_20
+   iload 0
+   goto If_end_21
+If_else_20:
+   iload 1
+   iload 0
+   iload 1
+   irem
+   invokestatic defs/defs/gcd(II)I
+If_end_21:
+   ireturn
 .end method
 \end{lstlisting}