Last active
December 23, 2015 10:58
-
-
Save okram/6624715 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
// MONAD DEFINITION | |
public abstract class Monad<S, E> { | |
protected final Monad<?, S> start; | |
public Monad(Monad<?, S> start) { | |
this.start = start; | |
} | |
public <T> Monad<E, T> map(Function<E, T> function) { | |
return new MapMonad<>(this, function); | |
} | |
public <T> Monad<E, T> flatMap(Function<E, Iterable<T>> function) { | |
return new FlatMapMonad<E, T>(this, function); | |
} | |
public Monad<E, E> filter(Predicate<E> predicate) { | |
return new FilterMonad<>(this, predicate); | |
} | |
public abstract E next(); | |
public abstract boolean hasNext(); | |
public static <T> Monad<T, T> of(final Iterator<T> iterator) { | |
return new Monad<T, T>(null) { | |
public T next() { | |
return (T) iterator.next(); | |
} | |
public boolean hasNext() { | |
return iterator.hasNext(); | |
} | |
}; | |
} | |
} | |
// USING THE MONAD TO TRAVERSE A GRAPH WITH EXPLICIT LAMBDA OPERATIONS | |
Monad m = Monad.of(g.query().vertices().iterator()) | |
.flatMap(v -> v.query().direction(Direction.OUT).vertices()) | |
.<String>map(v -> v.getValue("name")) | |
.filter(s -> s.contains("o")); | |
//// SYSTEM.OUT.PRINTLN OF WHILE(HASNEXT()) | |
lop | |
josh | |
lop | |
lop | |
//// EXTEND THE MONAD NOW WITH PREDEFINED LAMBDAS | |
public Monad<Vertex, Vertex> out(final String... labels) { | |
return new FlatMapMonad<Vertex, Vertex>((Monad) this, v -> v.query().labels(labels).direction(Direction.OUT).vertices()); | |
} | |
//// NOW YOU CAN TRAVERSE USING GREMLIN TERMS | |
Monad m = Monad.of(g.query().vertices().iterator()) | |
.out() | |
.<String>map(v -> v.getValue("name")) | |
.filter(s -> s.contains("o")); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment