Created
January 9, 2018 01:18
A demonstration of haskell-style pattern matching in java
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
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: