Skip to content

Instantly share code, notes, and snippets.

@jleedev
Created November 18, 2011 15:26
Show Gist options
  • Select an option

  • Save jleedev/1376745 to your computer and use it in GitHub Desktop.

Select an option

Save jleedev/1376745 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Either<Integer, String> x;
if (scan.hasNextInt()) {
x = Either.l(scan.nextInt());
} else {
x = Either.r(scan.nextLine());
}
String message = x.apply(new Cases<Integer, String, String>() {
@Override
public String l(Integer n) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < n; i++) {
result.append("moo");
if (i < n && n > 1) {
result.append(" ");
}
}
return result.toString();
}
@Override
public String r(String msg) {
return "No cows because: " + msg;
}
});
System.out.println(message);
}
}
interface Cases<L, R, V> {
public V l(L l);
public V r(R r);
}
class Either<L, R> {
private boolean hasL = false;
private boolean hasR = false;
private L l;
private R r;
private Either(L l, R r, boolean hasL, boolean hasR) {
this.l = l;
this.r = r;
this.hasL = hasL;
this.hasR = hasR;
}
public <V> V apply(Cases<L, R, V> f) {
if (hasL) {
return f.l(l);
} else {
return f.r(r);
}
}
public static <L, R> Either<L, R> l(L l) {
return new Either<L, R>(l, null, true, false);
}
public static <L, R> Either<L, R> r(R r) {
return new Either<L, R>(null, r, false, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment