alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

package test0016;

class Seq<E> {
	E head;
	Seq<E> tail;
	Seq() {
		this(null, null);
	}
	boolean isEmpty() {
		return this.tail == null;
	}
	Seq(E head, Seq<E> tail) {
		this.head = head;
		this.tail = tail;
	}
	<T> Seq> zip(Seq that) {
		if (this.isEmpty() || that.isEmpty())
			return new Seq<Pair();
		else
			return new Seq<Pair(
				new Pair<E,T>(this.head, that.head),
					this.tail.zip(that.tail));
	}
	@Override
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		if (head != null) {
			buffer.append(head);
		}
		if (tail != null) {
			buffer.append(tail);
		}
		return String.valueOf(buffer);
	}
	public class Zipper<T> {
		Seq<Pair zip(Seq that) {
			if (Seq.this.isEmpty() || that.isEmpty())
				return new Seq<Pair();
			else
				return new Seq<Pair(
					new Pair<E,T>(Seq.this.head, that.head),
						Seq.this.tail.zip(that.tail));
		}
	}
}
class Pair<A, B> {
	A fst;
	B snd;
	
	Pair(A a, B b) {
		this.fst = a;
		this.snd = b;
	}
	@Override
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("(");
		buffer.append(fst);
		buffer.append(", ");
		buffer.append(snd);
		buffer.append(")");
		return String.valueOf(buffer);
	}
	@Override
	public boolean equals(Object other) {
		return other instanceof Pair &&
				equals(fst, ((Pair)other).fst) &&
				equals(snd, ((Pair)other).snd);
	}
	private boolean equals(Object x, Object y) {
		return x == null && y == null || x != null && x.equals(y);
	}
}
public class X {
	public static void main(String[] args) {
		Seq<String> strs = new Seq("a", new Seq("b", new Seq()));
		Seq<Number> nums = new Seq(new Integer(1), new Seq(new Double(1.5), new Seq()));
		Seq<String>.Zipper zipper = strs.new Zipper();
		Seq<Pair combined = zipper.zip(nums);
		System.out.println(combined);
	}
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.