Skip to content

Instantly share code, notes, and snippets.

@monzee
Last active April 22, 2017 04:32
Show Gist options
  • Save monzee/987f2588e4283bdc0cba0cdebd87558e to your computer and use it in GitHub Desktop.
Save monzee/987f2588e4283bdc0cba0cdebd87558e to your computer and use it in GitHub Desktop.
ADT codegen reference
import java.util.function.Function;
public interface Adt {
static void main(String[] args) {
map(OptionOf.some(100), String::valueOf).match(new Option<String>() {
@Override
public void none() {
System.out.println("NONE!");
}
@Override
public void some(String t) {
System.out.println(t);
}
});
}
static <T, U> OptionOf<U> map(OptionOf<T> tOption, Function<T, U> f) {
return tOption.match(new OptionTo<T, OptionOf<U>>() {
@Override
public OptionOf<U> none() {
return OptionOf.none();
}
@Override
public OptionOf<U> some(T t) {
return OptionOf.some(f.apply(t));
}
});
}
}
// @Case
interface Option<T> {
void none();
void some(T t);
}
// everything below can be generated from the case interface
interface OptionTo<T, U> {
U none();
U some(T t);
}
abstract class OptionOr<T> implements Option<T> {
public abstract void orElse();
@Override
public void none() {
orElse();
}
@Override
public void some(T t) {
orElse();
}
}
abstract class OptionOrTo<T, U> implements OptionTo<T, U> {
public abstract U orElse();
@Override
public U none() {
return orElse();
}
@Override
public U some(T t) {
return orElse();
}
}
abstract class OptionOf<T> {
private OptionOf() {}
public abstract void match(Option<T> of);
public static <T> OptionOf<T> none() {
return new OptionOf<T>() {
@Override
public void match(Option<T> of) {
of.none();
}
};
}
public static <T> OptionOf<T> some(final T t) {
return new OptionOf<T>() {
@Override
public void match(Option<T> of) {
of.some(t);
}
};
}
public <U> U match(final OptionTo<T, U> to) {
return new Option<T>() {
U u; {
match(this);
}
@Override
public void none() {
u = to.none();
}
@Override
public void some(T t) {
u = to.some(t);
}
}.u;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment