相关疑难解决方法(0)

使用类型类约束将函数转换为采用显式类型类字典的函数

众所周知,实现Haskell类型类的一种方法是通过'类型类词典'.(这当然是ghc中的实现,尽管我强制要求其他实现是可能的.)为了解决这个问题,我将简要介绍一下这是如何工作的.类声明就像

class (MyClass t) where
  test1 :: t -> t -> t
  test2 :: t -> String
  test3 :: t
Run Code Online (Sandbox Code Playgroud)

可以机械地转换为数据类型的定义,如:

data MyClass_ t = MyClass_ {
  test1_ :: t -> t -> t,
  test2_ :: t -> String,
  test3_ :: t,
  }
Run Code Online (Sandbox Code Playgroud)

然后我们可以将每个实例声明机械地转换为该类型的对象; 例如:

instance (MyClass Int) where
  test1 = (+)
  test2 = show
  test3 = 3
Run Code Online (Sandbox Code Playgroud)

变成

instance_MyClass_Int :: MyClass_ Int
instance_MyClass_Int =  MyClass_ (+) show 3
Run Code Online (Sandbox Code Playgroud)

类似地,具有类型类约束的函数可以变成一个带有额外参数的函数; 例如:

my_function :: (MyClass t) => t -> String
my_function …
Run Code Online (Sandbox Code Playgroud)

haskell typeclass

9
推荐指数
1
解决办法
325
查看次数

标签 统计

haskell ×1

typeclass ×1