Created
January 9, 2018 01:18
-
-
Save anonymous/0eea8d3768c571a9230f54fd31d43ba0 to your computer and use it in GitHub Desktop.
A demonstration of haskell-style pattern matching in java
This file contains 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
public abstract class Maybe<V> | |
{ | |
public abstract <T> T match(Function<V, T> some, Supplier<T> none); | |
public abstract void match(Consumer<V> some, Runnable none); | |
... | |
private static class Nothing<U> extends Maybe<U> | |
{ | |
... | |
public <T> T match(Function<U, T> some, Supplier<T> none) | |
{ | |
return none.get(); | |
} | |
public void match(Consumer<U> some, Runnable none) | |
{ | |
none.run(); | |
} | |
... | |
} | |
private static class Just<V> extends Maybe<V> | |
{ | |
final V value; | |
... | |
public <T> T match(Function<V, T> some, Supplier<T> none) | |
{ | |
return some.apply(value); | |
} | |
public void match(Consumer<V> some, Runnable none) | |
{ | |
some.accept(value); | |
} | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: