结合和交换之间的区别

Difference between associative and commutative

我正在尝试理解幺半群中的关联。

书上说:

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

例如:

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

关于交换:

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.

上面的例子是结合律和交换律,但有什么区别呢? 我看不出区别。

如果幺半群运算是可交换的,我们将有 "a"<>"b" ≡ "b"<>"a"。但很明显,"ab""ba" 不是同一个字符串。

关联性是一个比较弱的属性,实际上人们通常认为它是任何操作的“obvious/trivial”。因此,让我们看一下 关联的操作——事实上,它很容易找到,例如减法:

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

大多数操作既不是关联的也不是交换的。许多操作是关联的但不是可交换的。你很少会找到一个可交换但不结合的操作,尽管再次构造它很容易; an example from Maths.SE:

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

这继承了乘法的交换性,但由于偏移 1 而不是结合性的。

Prelude> 0 & (1 & 2)
1
Prelude> (0 & 1) & 2
3

以字符串拼接为例。假设您使用的语言使用 + 进行字符串连接。这是自然关联的,因为分组无关紧要:

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

但操作数顺序绝对重要:

"a" + "b" = "ab"
"b" + "a" = "ba"

结合但不交换:

矩阵乘法是结合的,但不是交换的。

(AB)C = A(BC)

但是:

AB != BA

可交换但不可结合:

两个数之差的绝对值是可交换的,但不是结合的。

|a - b| = |b - a|

但是:

||a - b| - c| != |a - |b - c||