Difference between associative and commutative
I am trying to understand associativity in monoid.
From the book it says:
Associativity simply says that you can chain your arguments in different ways and the result will be the same.
For example:
Prelude> (1 + 9001) + 9001
18003
Prelude> 1 + (9001 + 9001)
18003
And about commutative ones:
This is not as strong a property as an operation that is commutative or commutative. Commutative means that you can change the order of the arguments and get the same result. Addition and multiplication are commutative, but (++) for a list type is only associative.
The above example is associative and commutative, but what's the difference? I don't see the difference.
source to share
Take string concatenation as an example. Let's say you are using a language that you use +
to concatenate strings. This is naturally associative, since the grouping doesn't matter:
("a" + "b") + "c" == "abc"
"a" + ("b" + "c") == "abc"
But the order of the operands definitely matters:
"a" + "b" = "ab"
"b" + "a" = "ba"
source to share
Associative but not commutative:
Matrix multiplication is associative but not commutative.
(AB)C = A(BC)
But:
AB != BA
Commutative but not associative:
The absolute value of the difference between two numbers is commutative, but not associative.
|a - b| = |b - a|
But:
||a - b| - c| != |a - |b - c||
source to share
If the monoid operation were commutative, we would have "a"<>"b" ≡ "b"<>"a"
. But clearly, "ab"
and "ba"
are not the same line.
Associativity is a weaker property as people often consider it "obvious / trivial" for any operation. So let's look at an operation that is not associative - in fact, it's simple enough to find, for example. Subtraction:
5 - (3 - 1) = 3
(5 - 3) - 1 = 1
Most of the operations are neither associative nor commutative. Many operations are associative, but not commutative. You will rarely find an operation that is commutative but not associative, but easy to construct; example from Maths.SE :
(&) :: Int -> Int -> Int
x & y = x*y + 1
This inherits commutativity from multiplication, but is not associative due to bias 1
.
Prelude> 0 & (1 & 2)
1
Prelude> (0 & 1) & 2
3
source to share