20-CS-4003-001 Organization of Programming Languages Fall 2017
Expression Evaluation

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures

Order of Evaluation of Arguments

Scheme:

   (or (= 1 1) (/ 3 0))
   (or (= 1 1) (or (/ 3 0) (= 1 1)))
   (car (list (= 1 1) (/ 3 0)))

Haskell:

   (or (1 == 1) (1 == (/ 3 0)))
   head [1==1,1==(/ 3 0)]

Java:

   import java.util.*;

   interface h { boolean getIt(); }
   class b implements h {  
      public boolean getIt () {  
         return (1 == (3/0)); 
      } 
   }
   class c implements h {  
      public boolean getIt () {  
         return (1 == 1); 
      } 
   }

   public class a {
      public static void main (String args[]) {
         Vector <h> v = new Vector <h> ();
         boolean a = (1 == 1) || (1 == (3/0));
         v.add(new c());
         v.add(new b());
         boolean d = v.get(0).getIt() || 
                     v.get(1).getIt();
         System.out.println(a+" "+d);
      }
   }
 -  Scheme evaluates subexpression from left to right as long as further evaluation is necessary to evaluate the expression containing those arguments. The top two statements on the left evaluate to #t, bypassing the exception that would result from executing (/ 3 0). However, the third statement does raise an exception because, although the (/ 3 0) is not needed to evaluate the car, it is executed to complete the list which is inside the car.

Haskell also evaluates subexpressions from left to right but it is fully lazy so it does not evaluate some expression that is needed. The code to the left corresponds to the Scheme code above it. In both cases True is returned and no exception is raised.

Java also evaluates from left to right as needed for the expression the arguments are in. An exception raising expression such as (1 == (3/0)) can be wrapped inside a class method and in this way placed into some container such as a Vector. In this way, the evaluation of expressions can be delayed until their values are needed. The code to the left shows this. The variable d is obtained like (or (list (= 1 1) (/ 3 0))) in Scheme but has value True.