Thursday, November 1, 2007

Don't Forget Your Scheme!


Well, wasted half a day yesterday by forgetting my Scheme. Finally,
A&S came to the rescue, somehow remembered after wasting a lot of time,
that 'append!' was one of the examples in that book and the same stuff
basically can be done in Java too..

Here is the Scheme version:


 (define (append! x y)
   (set-cdr! (last-pair x) y)
 x)
Here last-pair is a procedure that returns the last pair in its argument:

 (define (last-pair x)
   (if (null? (cdr x))
       x
   (last-pair (cdr x))))

From there the Java version for append! or what we call, descructively
appending a list to another one while not instantiating another one is easy.
Though we have to instantiate a new ListNode...

         ListNode LastP = lastPair(list1);
  LastP.setNext(list2);   //setNext is set-cdr!
  return list1;

Here's the helper for Java...

      public static LNode lastPair(ListNode y){
 if (y.next().isEmpty()){
    return y;
 } else 
  return lastPair(y.next());
      }


Another instersting one is the Reverse method: 

Scheme Version:

       (define (reverse L)
 (reverse-helper L '( )) )
 
       (define (reverse-helper L so-far)
      (if (null? L) so-far
   (reverse-helper (cdr L) (cons (car L) so-far)) ) )

Java version works the sameway if we are writing the recursive one:

return reverseHelper (list1.next() ,  new LNode (list1.data(), sofar) );


No comments:

Just some daily notes ...

Powered By Blogger