Monday, February 16, 2015

Getting rid of those casts

Getting rid of the casts...the basic trick is getting the Iterator to provide Nodes instead of Ts.

I don't really like creating the HasList interface, and someone out there could do better.  I did try to remove it...and nothing fun happened.

Given the time I tried banging my head on this, I'd say the conclusion that this sucks stands.

I want to write the three line tail recursive version; the Java devil is making me do it.

self.jump(shark);


head = new Reverser<Node<T>>(head).reverse();

public class Reverser<T extends HasList<T>> implements Iterable<T>{
 T curr;
 Reverser(T head) {this.curr = head;}
 @Override public Iterator<T> iterator() {return new RIterator<T>(this);}
 public T reverse() {
  return StreamSupport.stream(spliterator(), false)
    .reduce(null, (reversed, item) -> {return curr.attachToFrontOf(reversed);} );
 }
}

class RIterator<T extends HasList<T>> implements Iterator<T> {
 private Reverser<T> curr;
 private T rest;
 RIterator(Reverser<T> reverser) {
  this.curr = reverser;
  rest = reverser.curr;
 }
 @Override public boolean hasNext() {return rest != null;}
 @Override public  T next() {
  curr.curr = rest;
  return rest = rest.getRest();
 }
}

interface  HasList<T> {
    T attachToFrontOf(T n);
    T getRest();
}

class Node<T> implements HasList<Node<T>>{
 T val;
 Node<T> list;
 
 @Override public Node<T> attachToFrontOf(Node<T> n) {
  list = n;
  return this;
 }
 @Override public Node<T> getRest() {return list;}
 
}

No comments:

Post a Comment