Wednesday, October 31, 2007

Deconstructing a Scheme recursive function and implementing it as a java method..


Deconstructing a Scheme recursive function and implementing it as a java method..
 
In scheme, to add an element to the end of the list we have the following procedure:

 (define (add-to-end-of-list list a)
     (if (null? list) '(a)
       (cons (car list) (add-to-end-of-list (cdr list) a)) ) )

This is recursive. And answer returns after it hits base case and everybody is happy!

Ecept for the stack I guess.

 
Amazing thing is, we can pretty much do the same in Java!
 
 public Lnodeadd (Object a) {

        return LnodeAddHelper (this, a);

 }

 private static LnodeAddHelper (Lnode L, Object a) {

        if (L.Empty()) {

                return new Lnode (a);

        } else {

                return new Lnode(L.first(), LnodeAddHelper (L.rest(), a)); 
                //the above line is mind blowing or what???

        }

 }

Here Lnode is the singly linked List. first() is car, rest() is cdr and the Lnode constructor is the cons.

No comments:

Just some daily notes ...

Powered By Blogger