Created
November 18, 2011 15:26
-
-
Save jleedev/1376745 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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