20-CS-4003-001 Organization of Programming Languages Fall 2017
Recursion

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures

Order of Evaluation of Arguments

Scheme:

  (define a 
    (lambda (x y) 
      (if (= x 1) 1 y)))

  (a 1 (/ 3 0))

  (define b 
    (lambda (x y) 
      (if (= x 1) 1 (y))))

  (b 1 (lambda () (/ 3 0)))

Haskell:

  multr l = foldr (\acc x -> acc*x) 1 l

  multl l = foldl (\acc x -> acc*x) 1 l

  mult l = 
    if l == [] then
       1
    else 
       (head l)*(mult (drop 1 l))

Java:

  public class mult {
     public static void main (String args[]) {
        int a[] = new int[]{ 1,2,3,4,5 };
        int total = 1;
        try  {
           for (int i=0 ; ; i++) total *= a[i];
        } catch (Exception e) { }
        System.out.println(total);
     }
  }

  import java.util.*;

  public class A {
     public static int mult (Vector  v) {
        if (v.isEmpty()) return 1;
        int n = v.get(0);
        v.removeElementAt(0);
        return n*mult(v);
     }

     public static void main (String args[]) {
        Vector  v = new Vector  ();
        v.add(2);
        v.add(3);
        v.add(4);
        v.add(5);
        System.out.println(mult(v));
     }
  }

  import java.util.*;

  public class B {
     public static int mult (Vector  v, int acc) {
        if (v.isEmpty()) return acc;
        int n = v.get(0);
        v.removeElementAt(0);
        return mult(v, n*acc);
     }

     public static void main (String args[]) {
        Vector  v = new Vector  ();
        v.add(2);
        v.add(3);
        v.add(4);
        v.add(5);
        System.out.println(mult(v, 1));
     }
  }

 -  If arguments are evaluated before the body of a procedure is executed they are said to be evaluated in applicative order. If the arguments are evaluated only if they are needed in the execution of the procedure, then they are evaluated in normal order. Scheme is an applicative order languages but can be adapted to a normal order evaluation role, if necessary. The arguments of program a are strictly evaluated in applicative order: the execution (a 1 (/ 3 0)) fails even though there is no need for (/3 0) to be evaluated. Program b now requires the second argument to be in a thunk. Execution of the argument is delayed until it is needed. Execution of (b 1 (lambda () (/ 3 0))) returns 1. Execution of (b 2 (lambda () (/ 3 0))) fails.