gpt4 book ai didi

haskell - 使用 Haskell 的类型系统来指定一个类服从额外的属性(即类型类的类型类)

转载 作者:行者123 更新时间:2023-12-04 07:06:28 26 4
gpt4 key购买 nike

当我们创建一个类型类时,我们通常假设它的函数必须服从一些属性。因此,对于它们各自的类型类,我们有 Monoid 和 Monad 定律。但是,如果有一些法则,比如关联性,我想指定多个类可能遵守也可能不遵守该法则?有没有办法在 Haskell 的类型系统中做到这一点?这种类型类的类型类想法在实践中是否可行?

这是代数中的一个激励示例:

class Addition x where
add :: x -> x -> x

class Multiplication x where
mult :: x -> x -> x

instance Addition Int where
add = (+)

instance Multiplication Int where
add = (*)

现在,如果我想指定对 Int 的加法是关联的和可交换的,我可以创建类和实例:
class (Addition x) => AssociativeAddition x where
class (Addition x) => CommutativeAddition x where

instance AssociativeAddition Int where
instance CommutativeAddition Int where

但这很麻烦,因为我必须为所有类创建所有可能的组合。我不能只创建 Associative 和 Commutative 类,因为如果加法是可交换的,但乘法不是(就像在矩阵中一样)怎么办?

我想做的是这样说:
class Associative x where

instance (Associative Addition, Commutative Addition) => Addition Int where
add = (+)

instance (Commutative Multiplication) => Multiplication Int where
mult = (*)

这可以做到吗?

(Haskell 的抽象代数包,如代数和构造代数,目前不这样做,所以我猜不是。但为什么不呢?)

最佳答案

您实际上可以使用最近的一些 GHC 扩展来做到这一点:

{-# LANGUAGE ConstraintKinds, KindSignatures, MultiParamTypeClasses #-}
import GHC.Exts (Constraint)

class Addition (a :: *) where
plus :: a -> a -> a

instance Addition Integer where
plus = (+)

class (c a) => Commutative (a :: *) (c :: * -> Constraint) where
op :: a -> a -> a

instance Commutative Integer Addition where
op = plus

关于haskell - 使用 Haskell 的类型系统来指定一个类服从额外的属性(即类型类的类型类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11729378/

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