ciu*_*can 17 functional-programming fortress algebraic-data-types abstract-algebra
我最近了解了函数式编程(在Haskell和Scala中).它的功能和优雅非常迷人.
但是当我遇到使用名为Monoid的代数结构的Monads时,我很惊讶并且很高兴看到我从数学中学到的理论知识在编程中得到了应用.
这个观察带来了一个问题:组,字段或环(参见其他代数结构)是否可以用于编程,以实现更多的抽象和代码重用目的,并实现类似数学的编程?
据我所知,名为Fortress的语言(在编译器完成后我肯定会喜欢任何语言)在其库代码中定义了这些结构.但到目前为止我只看到数字类型,我们已经熟悉了.它们还有其他用途吗?
最好的问候,ciun
sdc*_*vvc 10
您可以为许多结构建模.这是一个小组:
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)
Run Code Online (Sandbox Code Playgroud)
现在,您可以编写mult (Dual CAB, 5) (Dual CBA, 1)并获得结果.这将是S 3*组的计算?Z.您可以添加其他组,以任何可能的方式组合它们并使用它们进行计算.
类似的事情可以用环,字段,排序,向量空间,类别等来完成.不幸的是,Haskell的数字层次结构很糟糕,但是有数字前奏 试图解决这个问题.还有DoCon将它带到极端.对于类型类别的旅游(主要是由范畴论的动机),有Typeclassopedia 拥有的实例和应用的大名单.