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) );
Thursday, November 1, 2007
Don't Forget Your Scheme!
Subscribe to:
Post Comments (Atom)
Just some daily notes ...
Things I'm into now...
Blog Archive
-
▼
2007
(29)
-
▼
November
(14)
- Declaring an Edge Adjacency List Graph
- MaximallyBalanced or Complete Binary Tree
- Calculating the Height of a Tree
- Adding to a Circular Doubly Linked List
- 3 ways to REVERSE a list (singly linked)
- Reversing a List Iteratively!
- Doubling a Linked List
- Access Modifiers: public, private, proctecd, packa...
- End of HFJ
- Format Specifiers
- Collection class tidbits...
- Generic class definitions and one implementation
- doubling a List
- Don't Forget Your Scheme!
-
▼
November
(14)
No comments:
Post a Comment