Skip to content

Associative but not commutative

LI YUAN XIN edited this page Nov 30, 2020 · 3 revisions

Here's some small little experiment you can try out~

    Function<Integer, Integer> multiply = x -> x * x;
    Function<Integer, Integer> add = x -> x + x; 
    Function<Integer, Integer> subtract = x -> x - 1; 

    // proved: not commutative
    System.out.println(multiply.andThen(add).apply(2)); // add(multi(x)): (2 * 2) then  4 + 4 = 8
    System.out.println(add.andThen(multiply).apply(2)); // multi(add(x)): (2 + 2) then  4 * 4 = 16

    // proved: is associative
    System.out.println(add.compose(multiply).andThen(subtract).apply(2)); // h o (f o g) output: 7
    System.out.println(multiply.andThen(subtract.compose(add)).apply(2)); // (h o f) o g output: 7
Clone this wiki locally