Semigroups
A semigroup is an s type with a (<>)
binary operator:
GHC.Base
class Semigroup s where
(<>) :: s -> s -> s
The binary operator must obey one law: associativity.
Associativity
This law states that when combining more than two values, the positioning of parentheses does not matter:
x <> (y <> z) == (x <> y) <> z
For this reason, the parentheses are usually omitted, and we simply write x <> y <>
z
.
Instances
The list
type forms a semigroup with the (++)
operator:
GHC.Base
instance Semigroup [a] where
(<>) = (++)
The following example demonstrates the associativity of this operator:
*Main> [1,2] <> ([3] <> [4,5]) [1,2,3,4,5] *Main> ([1,2] <> [3]) <> [4,5] [1,2,3,4,5]
Likewise, numeric types form a semigroup with addition (+
) but also with multiplication (*
). Indeed, we have this, for example:
*Main> (1 + 2) + 3 6 *Main>...