您可以为许多结构建模。这是一组:
class Group a where
mult :: a -> a -> a
identity :: a
inverse :: a -> a
instance Group Integer where
mult = (+)
identity = 0
inverse = negate
-- S_3 (group of all bijections of a 3-element set)
data S3 = ABC | ACB | BAC | BCA | CAB | CBA
instance Group S3 where
mult ABC x = x
... -- some boring code
identity = ABC
inverse ABC = ABC
... -- remaining cases
-- Operations on groups. Dual:
data Dual a = Dual { getDual :: a }
instance Group a => Group (Dual a) where
mult (Dual x) (Dual y) = Dual (mult y x)
identity = Dual identity
inverse (Dual x) = Dual (inverse x)
-- Product:
instance (Group a, Group b) => Group (a,b) where
mult (x,y) (z,t) = (x `mult` z, y `mult` t)
identity = (identity, identity)
inverse (x,y) = (inverse x, inverse y)
现在,您可以编写mult (Dual CAB, 5) (Dual CBA, 1)
并获得结果。这将是组 S 3 * ⨯ Z 中的计算。您可以添加其他组,以任何可能的方式组合它们并与它们进行计算。
类似的事情可以用环、字段、排序、向量空间、类别等来完成。不幸的是,Haskell 的数字层次结构模型很糟糕,但是有一个数字前奏 试图解决这个问题。还有将它发挥到极致的DoCon 。对于类型类之旅(主要受范畴论启发),有Typeclassopedia ,其中包含大量示例和应用程序。