Recursion

Definition

The bread and butter of LISP is recursion. The following function when called will result in more calls to itself. This definition of a function actually calculates x to the power of y (for positive integer values of y) - and it works in Jatha! A recursive function can cause a stack overflow if it does not have a termination conditions that activate. It could be inferred that the termination condition is the critical part of a recursive definition otherwise an infinite loop would occur.

Common LISP Code

 (defun power (x y)
   (if (= y 0) 1
   (* x (power x (1- y)))))

(power 3 4)

Common LISP Output

POWER
81

Java Code

package jathaverify;
import org.jatha.*;
import org.jatha.dynatype.*;
import java.util.*;
public class Main  {

    public Main() {
    }

    public static void main(String[] args) {
        Jatha myLisp  = new Jatha(false, false);
        myLisp.init();
        myLisp.start();

        try {
            List lisp = new ArrayList();
            lisp.add("(defun power (x y) (if (= y 0) 1 (* x (power x (1- y)))))");
            lisp.add("(power 3 4)");
            Iterator i = lisp.iterator();
            while (i.hasNext()) {
                String query = i.next().toString();
                System.out.println(query + " = " + myLisp.eval(query));
             }

        } catch (Exception e) {
            System.err.println("LISP Exception: " + e);
        }

    }
}

Java Output (Jatha)

compile:
run:
(defun power (x y) (if (= y 0) 1 (* x (power x (1- y))))) = POWER
(power 3 4) = 81
BUILD SUCCESSFUL (total time: 0 seconds)

Result

Rock!