Skip to content

Instantly share code, notes, and snippets.

@jdegoes
Created February 11, 2014 15:28
Show Gist options
  • Save jdegoes/8937061 to your computer and use it in GitHub Desktop.
Save jdegoes/8937061 to your computer and use it in GitHub Desktop.
Pattern matching in Java 7
import fj.F;
import fj.P;
import fj.P2;
import fj.data.Either;
import fj.data.Option;
abstract class Pattern<A, B> {
abstract Option<B> match(A value);
<C> Pattern<A, Either<B, C>> or(final Pattern<A, C> that) {
return new Pattern<A, Either<B, C>>() {
@Override
Option<Either<B, C>> match(final A value) {
return Pattern.this.match(value).map(Either.<B, C>left_()).orElse(that.match(value).map(Either.<B, C>right_()));
}
};
}
public static <A, C, D> Pattern<A, P2<C, D>> Tuple2(final Pattern<Object, C> _1, final Pattern<Object, D> _2) {
return new Pattern<A, P2<C, D>>() {
@Override
Option<P2<C, D>> match(final A value0) {
if (value0 instanceof P2) {
final P2 value = (P2)value0;
return Option.liftM2(new F<C, F<D, P2<C, D>>>() {
@Override
public F<D, P2<C, D>> f(final C c) {
return new F<D, P2<C, D>>() {
@Override
public P2<C, D> f(final D d) {
return P.p(c, d);
}
};
}
}).f(_1.match(value._1())).f(_2.match(value._2()));
} else return Option.none();
}
};
}
public static <A> Pattern<A, A> K(final A constant) {
return new Pattern<A, A>() {
@Override
Option<A> match(final A value) {
if (constant.equals(value)) return Option.some(value);
else return Option.none();
}
};
}
public static <A> Pattern<A, A> any() {
return new Pattern<A, A>() {
@Override
Option<A> match(final A value) {
return Option.some(value);
}
};
}
public static <A, B> Pattern<A, B> Int(final Pattern<Integer, B> pattern) {
return new Pattern<A, B>() {
@Override
Option<B> match(final A value) {
if (value instanceof Integer) return pattern.match((Integer)value);
else return Option.none();
}
};
}
public static void main(String[] args) {
Pattern<Object, P2<Integer, Integer>> pattern = Tuple2(Int(K(4)), Int(Pattern.<Integer>any()));
System.out.println(pattern.match(P.p(4, 1)));
System.out.println(pattern.match(P.p(5, 1)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment