Last active
March 15, 2020 16:19
-
-
Save dwickstrom/316b61e22d597ee67849ece1aa3be69e to your computer and use it in GitHub Desktop.
Contravariant Predicate Functor
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
import java.util.List; | |
import java.util.Objects; | |
import java.util.function.Function; | |
import java.util.function.Predicate; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
class Scratch { | |
public static void main(String[] args) { | |
System.out.println(getCertainThings()); | |
} | |
@FunctionalInterface | |
interface Pred<T> extends Predicate<T> { | |
default <U> Pred<U> contramap(Function<? super U, ? extends T> fn) { | |
return t -> this.test(fn.apply(t)); | |
} | |
default Pred<T> negate() { | |
return t -> !this.test(t); | |
} | |
default Pred<T> and(Pred<? super T> other) { | |
Objects.requireNonNull(other); | |
return t -> this.test(t) && other.test(t); | |
} | |
default Pred<T> or(Pred<? super T> other) { | |
Objects.requireNonNull(other); | |
return t -> this.test(t) || other.test(t); | |
} | |
} | |
static class SomeThing { | |
private final String value; | |
SomeThing(String value) { | |
this.value = value; | |
} | |
String getValue() { | |
return value; | |
} | |
public String toString() { | |
return value; | |
} | |
} | |
private static Pred<String> containsSubString(String ss) { | |
return s -> s.contains(ss); | |
} | |
private static Pred<String> lengthEquals(int l) { | |
return s -> s.length() == l; | |
} | |
private static List<SomeThing> getCertainThings() { | |
return Stream.of( | |
new SomeThing("foo"), | |
new SomeThing("bar"), | |
new SomeThing("bazes"), | |
new SomeThing("quxors")) | |
.filter(lengthEquals(3).and(containsSubString("ar")).contramap(SomeThing::getValue)) | |
.collect(Collectors.toList()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment