hws/hw08.tex
changeset 1010 ae9ffbf979ff
parent 957 34b3aeb65fbe
equal deleted inserted replaced
1009:432d027aa6f7 1010:ae9ffbf979ff
   112 
   112 
   113 \solution{
   113 \solution{
   114 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).
   114 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).
   115 }  
   115 }  
   116 
   116 
       
   117 \item The JVM method given below is code for the following recursive function
       
   118 
       
   119 \begin{lstlisting}[numbers=none]
       
   120 def add(x, y) = if x == 0 then y else add(x - 1, y + 1)
       
   121 \end{lstlisting}
       
   122 
       
   123 Rewrite the JVM code such that the recursive call at the end is removed.
       
   124 
       
   125 \begin{lstlisting}[language=JVMIS,numbers=none]
       
   126 .method public static add(II)I
       
   127 .limit locals 2
       
   128 .limit stack 7
       
   129   iload 0
       
   130   ldc 0
       
   131   if_icmpne If_else_4
       
   132   iload 1
       
   133   goto If_end_5
       
   134 If_else_4:
       
   135   iload 0
       
   136   ldc 1
       
   137   isub
       
   138   iload 1
       
   139   ldc 1
       
   140   iadd
       
   141   invokestatic defs/defs/add(II)I  ;; recursive call
       
   142 If_end_5:
       
   143   ireturn
       
   144 .end method
       
   145 \end{lstlisting}
       
   146 
       
   147 \solution{
       
   148 \begin{lstlisting}[language=JVMIS,numbers=none]
       
   149 .method public static add(II)I
       
   150 .limit locals 2
       
   151 .limit stack 7
       
   152 add2_Start:
       
   153   iload 0
       
   154   ldc 0
       
   155   if_icmpne If_else_4
       
   156   iload 1
       
   157   goto If_end_5
       
   158 If_else_4:
       
   159   iload 0
       
   160   ldc 1
       
   161   isub
       
   162   iload 1
       
   163   ldc 1
       
   164   iadd 
       
   165   istore 1
       
   166   istore 0
       
   167   goto add2_Start
       
   168 If_end_5:
       
   169   ireturn
       
   170 .end method
       
   171 \end{lstlisting}
       
   172 }
       
   173 
   117 
   174 
   118 \item Explain what is meant by the terms lazy evaluation and eager
   175 \item Explain what is meant by the terms lazy evaluation and eager
   119   evaluation.
   176   evaluation.
   120 
   177 
   121   \solution{ Lazy evaluation only evaluates expressions when they are
   178   \solution{ Lazy evaluation only evaluates expressions when they are