hws/hw08.tex
changeset 1010 ae9ffbf979ff
parent 957 34b3aeb65fbe
--- a/hws/hw08.tex	Sun Oct 12 12:50:16 2025 +0100
+++ b/hws/hw08.tex	Fri Oct 17 11:20:49 2025 +0100
@@ -114,6 +114,63 @@
 Scala cannot generate jumps in between different methods (to which functions are compiled to). So cannot eliminate the tail-calls. Haskell for example can do this because it compiles the code in a big ``blob'' inside a main-method (similar to the WHILE language).
 }  
 
+\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)
+\end{lstlisting}
+
+Rewrite the JVM code such that the recursive call at the end is removed.
+
+\begin{lstlisting}[language=JVMIS,numbers=none]
+.method public static add(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
+.end method
+\end{lstlisting}
+
+\solution{
+\begin{lstlisting}[language=JVMIS,numbers=none]
+.method public static add(II)I
+.limit locals 2
+.limit stack 7
+add2_Start:
+  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 
+  istore 1
+  istore 0
+  goto add2_Start
+If_end_5:
+  ireturn
+.end method
+\end{lstlisting}
+}
+
 
 \item Explain what is meant by the terms lazy evaluation and eager
   evaluation.