Skip to content

Instantly share code, notes, and snippets.

@maxov
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxov/01f662b87fccfee0373c to your computer and use it in GitHub Desktop.
Save maxov/01f662b87fccfee0373c to your computer and use it in GitHub Desktop.
java heterogenous lists madness
public abstract class HList {
public abstract int length();
public static H0 of() {
return Nil;
}
public static <T1> H1<T1> of(T1 v1) {
return new H1<T1>(v1);
}
public static <T1, T2> H2<T1, T2> of(T1 v1, T2 v2) {
return new H2<T1, T2>(v1, v2);
}
public static <T1, T2, T3> H3<T1, T2, T3> of(T1 v1, T2 v2, T3 v3) {
return new H3<T1, T2, T3>(v1, v2, v3);
}
public static <T1, T2, T3, T4> H4<T1, T2, T3, T4> of(T1 v1, T2 v2, T3 v3, T4 v4) {
return new H4<T1, T2, T3, T4>(v1, v2, v3, v4);
}
public static <T1, T2, T3, T4, T5> H5<T1, T2, T3, T4, T5> of(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) {
return new H5<T1, T2, T3, T4, T5>(v1, v2, v3, v4, v5);
}
public static class H0 extends HList {
@Override
public int length() {
return 0;
}
}
public static H0 H0 = new H0();
public static class H1<T1> extends Cons<T1, H0> {
public H1(T1 v1) {
super(v1, H0);
}
}
public static class H2<T1, T2> extends Cons<T1, H1<T2>> {
public H2(T1 v1, T2 v2) {
super(v1, new H1<T2>(v2));
}
}
public static class H3<T1, T2, T3> extends Cons<T1, H2<T2, T3>> {
public H3(T1 v1, T2 v2, T3 v3) {
super(v1, new H2<T2, T3>(v2, v3));
}
}
public static class H4<T1, T2, T3, T4> extends Cons<T1, H3<T2, T3, T4>> {
public H4(T1 v1, T2 v2, T3 v3, T4 v4) {
super(v1, new H3<T2, T3, T4>(v2, v3, v4));
}
}
public static class H5<T1, T2, T3, T4, T5> extends Cons<T1, H4<T2, T3, T4, T5>> {
public H5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) {
super(v1, new H4<T2, T3, T4, T5>(v2, v3, v4, v5));
}
}
private static class Cons<H, T extends HList> extends HList {
private final H head;
private final T tail;
public Cons(H head, T tail) {
this.head = head;
this.tail = tail;
}
public H head() {
return head;
}
public T tail() {
return tail;
}
@Override
public int length() {
return 1 + this.tail.length();
}
public static <H, T extends HList> Cons<H, T> of(H h, T v) {
return new Cons<H, T>(h, v);
}
}
}
public class PlayingAround {
static {
HList.of(new StringBuilder(), 3, "mystring").head().append("ab");
HList.of(new StringBuilder(), 3, "mystring").length();
HList.of("abc", "cde").tail().tail().length();
HList.H2<Integer, String> l = HList.of(new StringBuilder(), 3, "mystring").tail();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment