Skip to content

Instantly share code, notes, and snippets.

@jnape
Last active November 24, 2017 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnape/6eaf659ec9d8ff67f0da6ca20f6fbb62 to your computer and use it in GitHub Desktop.
Save jnape/6eaf659ec9d8ff67f0da6ca20f6fbb62 to your computer and use it in GitHub Desktop.
public static class SetIsNotAFullyFaithfulFunctor {
public static void main(String[] args) {
class Mod {
private final int mod;
private final int value;
Mod(int mod, int value) {
this.mod = mod;
this.value = value;
}
int getValue() {
return value;
}
@Override
public int hashCode() {
return mod * 31;
}
@Override
public boolean equals(Object other) {
// the problem is Set's reliance on structural equality, which is not guaranteed, nor should it be
return other instanceof Mod && (value % mod) == (((Mod) other).value % mod);
}
}
Function<Integer, Mod> g = x -> new Mod(2, x);
Function<Mod, Integer> f = Mod::getValue;
// map f . map g
Map.<Mod, Integer>map(f).andThen(toCollection(HashSet::new)) // Set[1, 2]
.compose(map(g)).andThen(toCollection(HashSet::new)) // Set[Mod(2,1), Mod(2,2)]
.apply(asList(1, 2, 3));
System.out.println();
System.out.println("vs");
System.out.println();
// map (f . g)
map(f.compose(g)).andThen(toCollection(HashSet::new)) // Set[1, 2, 3]
.apply(asList(1, 2, 3))
.forEach(System.out::println);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment