https://github.com/sidmishraw/visitors
Algebraic Data Types and Pattern matching in Java.
https://github.com/sidmishraw/visitors
adt java8 monads
Last synced: 1 day ago
JSON representation
Algebraic Data Types and Pattern matching in Java.
- Host: GitHub
- URL: https://github.com/sidmishraw/visitors
- Owner: sidmishraw
- Created: 2018-01-10T08:01:07.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-01-10T08:01:23.000Z (over 8 years ago)
- Last Synced: 2025-01-15T06:48:11.593Z (over 1 year ago)
- Topics: adt, java8, monads
- Language: Java
- Size: 58.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Pattern Matching in Java using Visitor Design Pattern
\- Sid
## Motivation
Simulate Haskell like Algebraic Data Types and pattern matching in Java. Follow it up with Monads.
```haskell
test :: Maybe Int -> Int
test x = case x of
Nothing -> error "Nothing"
(Just y) -> y
```
```java
/**
* Just a funky eval method that checks the type of data.
* Returns {@code true} for {@link Just} instance and {@code false} for {@link Nothing} instance.
*
* @param maybe
* The {@link Maybe} instance.
* @return True or False depending on the concrete type.
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static T test(Maybe maybe) throws Exception {
//
// Pattern matching simulated using Visitor Pattern.
//
MaybeVisitor mVisitor = new MaybeVisitor() {
/**
* The value used for holding the values for the time-being.
*/
private T value;
@Override
public void visit(Nothing nothing) {
//
// simulates Haskell's `Nothing -> -- stuff --`
//
System.out.println("Visiting a Nothing instance");
this.value = null;
}
@Override
public void visit(Just just) {
//
// simulates Haskell's `(Just e) -> -- do stuff --`
//
System.out.println("Visiting a Just instance with value = " + just.getTheValue());
this.value = just.getTheValue();
}
@SuppressWarnings("unused")
public T getValue() {
return this.value;
}
};
//
// simulates Haskell's `case t of`
//
maybe.accept(mVisitor);
return (T) mVisitor.getClass().getMethod("getValue").invoke(mVisitor);
}
```
## Verdict
* Java version is very verbose.
* Scala's case classes are very good for this scenario. I might move over to Scala to design Monads and Pattern matching DSLs.