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

Recursion |

**Tail Recursion**

Scheme: (define mult (lambda (l) (if (null? l) 1 (* (car l) (mult (cdr l)))))) (mult '(5 4 6 7 0 6 7)) (define mult^ (lambda (acc l) (if (null? l) acc (mult^ (* (car l) acc) (cdr l))))) (mult^ 1 '(5 4 6 7 7 8)) 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 |
- |
A recursive function is tail recursive if the final result of the
recursive call is the final result of the function itself. If the
result of the recursive call must be further processed (say, by adding
1 to it, or consing another element onto the beginning of it), it is
not tail recursive. Formally, in Haskell, let a function be defined
as f = t where f is a name and t is a lambda-term.
Then f is tail recursive iff f occurs tail recursively in
t and f occurs tail recursively in t iff
f occurs in t and any of the following holds:
`t`is variable;`t`is`(\var -> t0)`and`f`occurs tail recursively in`t0`;`t`is`t0 t1`and`f`occurs tail recursively in`t0`and does not occur in`t1`;`t`is`let bs in t0`and`f`occurs tail recursively in`t0`and for each binder`var = t1`in`bs`,`f`does not occur in`t1`;`t`is`case t0`of`bs`and`f`does not occur in`t0`and for each branch`b`in`bs`,`f`does not occur or occurs tail recursively in`b`;
b" where b has form
D vars -> t (where D is some data constructor and
vars is a sequence of names), is \vars -> t instead of
b (http://www.haskell.org/haskellwiki/Tail_recursion).
The Scheme program
Haskell programs
The Java program of |
||