Skip to content

Instantly share code, notes, and snippets.

@jneen
Last active December 20, 2015 11:39
Show Gist options
  • Save jneen/6124618 to your computer and use it in GitHub Desktop.
Save jneen/6124618 to your computer and use it in GitHub Desktop.
// what i assume the callbacks look like
abstract class Callback<T> {
abstract void run(T data);
}
// the binding function a -> m b
abstract class Step<T, U> {
abstract Action<U> into(final T data);
}
// a monad instance
abstract class Action<T> {
abstract void force(Callback<T> cb);
// monadic "return"
static <T> Action<T> of(final T value) {
return new Action<T>() {
void force(final Callback<T> cb) { cb.run(value); }
};
}
// monadic "bind"
<U> Action<U> chain(final Step<T, U> step) {
return new Action<U>() {
void force(final Callback<U> cb) {
Callback<T> firstCallback = new Callback<T>() {
void run(final T data) {
step.into(data).force(cb);
}
};
}
};
}
// monadic "then" to sequence actions
<U> Action<U> then(final Action<U> next) {
return this.chain(new Step<T, U>() {
Action<U> into(T _) { return next; }
});
}
// override the result
<U> Action<U> result(final U res) {
return this.then(Action.of(res));
}
// perform an action, but preserve the previous value
<U> Action<T> skip(final Action<U> action) {
return this.chain(new Step<T, T>() {
Action<T> into(final T res) {
return action.result(res);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment