gpt4 book ai didi

functional-programming - 除了幺半群之外,函数式编程中是否使用了任何代数结构?

转载 作者:行者123 更新时间:2023-12-03 14:10:34 25 4
gpt4 key购买 nike

我最近开始了解函数式编程(在 Haskell 和 Scala 中)。它的功能和优雅非常迷人。

但是当我遇到使用名为 Monoid 的代数结构的 Monads 时,我很惊讶也很高兴看到我从数学中学到的理论知识被用于编程。

这个观察让我想到了一个问题:组、域或环(参见 Algebraic Structures 其他)可以用于编程以实现更多抽象和代码重用目的并实现类似数学的编程吗?

据我所知,名为 Fortress 的语言(一旦编译器完成,我肯定会更喜欢任何语言)在其库代码中定义这些结构。但到目前为止,我看到的唯一用途是我们已经熟悉的数字类型。它们还有其他用途吗?

最好的祝福,

最佳答案

您可以为许多结构建模。这是一组:

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)并得到一个结果。这将是组 S3* ⨯ Z 中的计算。您可以添加其他组,以任何可能的方式组合它们并与它们进行计算。

类似的事情可以用环、字段、排序、向量空间、类别等来完成。不幸的是,Haskell 的数字层次模型很糟糕,但是有 numeric prelude试图解决这个问题。还有 DoCon这将其发挥到了极致。类型类之旅(主要受范畴理论启发),有 Typeclassopedia其中有大量示例和应用程序。

关于functional-programming - 除了幺半群之外,函数式编程中是否使用了任何代数结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3331287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com