20-CS-4003-001 Organization of Programming Languages Fall 2018
Iteration

Lambda calculus, Type theory, Formal semantics, Program analysis

Prev     Next     All lectures

Looping

 Scheme: ``` (define mult (lambda (l) (if (null? l) 1 (* (car l) (mult (cdr l)))))) (mult '(5 4 6 7 0 6 7)) (map (lambda (x) (+ x 1)) '(1 2 3 4)) ``` Haskell: ``` multa l = if (l == []) then 1 else (head l)*(multa (drop 1 l)) multb l = last acc where acc = 1:[ y*x | y <- acc | x <- l ] multc l = foldr (\acc x -> acc*x) 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); } } ``` - The principle means of iteration in Scheme is recursion and map. Both are illustrated to the left. construct. Haskell admits recursion and map as well as shown to the left in the first and third examples. The third example shows a form of map which folds a list based on a given function which, in this case, multiplies a list element by the accumulated value. Haskell also makes use of list comprehensions to perform iteration as shown in the middle example. This form of iteration is very important since Haskell does not support assignment, a list comprehension may be used to update current state as shown in the example. Java provides recursion but this is not shown. The principle forms of iteration in Java are for and while loops.