Last active
November 24, 2017 23:57
-
-
Save jnape/6eaf659ec9d8ff67f0da6ca20f6fbb62 to your computer and use it in GitHub Desktop.
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
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