Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between associative and commutative

I am trying to understand associative in monoid.

From the book, it says:

Associativity simply says that you can associate the arguments of your operation differently and the result will be the same.

For example:

Prelude> (1 + 9001) + 9001
18003
Prelude> 1 + (9001 + 9001)
18003

And about commutative:

This is not as strong a property as an operation that commutes or is commutative. Commutative means you can reorder the arguments and still get the same result. Addition and multiplication are commutative, but (++) for the list type is only associative.

The example above is associative and commutative but what is the difference? I can not see the difference.

like image 843
softshipper Avatar asked Jun 26 '17 12:06

softshipper


3 Answers

Take string concatenation as an example. Suppose you're using a language which uses + for string concatenation. That's naturally associative, as the grouping doesn't matter:

("a" + "b") + "c" == "abc"
"a" + ("b" + "c") == "abc"

But the operand order definitely matters:

"a" + "b" = "ab"
"b" + "a" = "ba"
like image 165
Jon Skeet Avatar answered Oct 20 '22 06:10

Jon Skeet


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||
like image 25
Anton Xue Avatar answered Oct 20 '22 08:10

Anton Xue


If the monoid operation were commutative, we would have "a"<>"b" ≡ "b"<>"a". But clearly, "ab" and "ba" aren't the same string.

Associativity is a rather weaker property, in fact people often consider it as “obvious/trivial” for about any operation. So let's look at an operation that's not associative – in fact that's simple enough to find, e.g. subtraction:

5 - (3 - 1) = 3
(5 - 3) - 1 = 1

Most operations are neither associative nor commutative. Many operations are associative but not commutative. You'll seldom find an operation that's commutative but not associative though again it's easy to construct this; an example from Maths.SE:

(&) :: Int -> Int -> Int
x & y = x*y + 1

This inherits commutativity from the multiplication, but is not associative because of the offset 1.

Prelude> 0 & (1 & 2)
1
Prelude> (0 & 1) & 2
3
like image 31
leftaroundabout Avatar answered Oct 20 '22 06:10

leftaroundabout