动态调度,智能构造函数,模板Haskell?
-
22-10-2019 - |
题
我在想,Haskell的模板应该有一种方法来采取这一部分:
class Shape_ a where
...
type Radius = Double
data Circle = Circle Radius
instance Shape_ Circle where
...
并自动得出此部分:
-- derive the data type
data Shape = forall a. Shape_ a => Shape a
-- derive smart constructors similar to the original constructor
circle :: Radius -> Shape
circle r = Shape (Circle r)
这是在模板Haskell中完成的吗?可以在TH中完成吗?可以在普通的旧哈斯克尔中做类似的事情,而不必手工写出所有智能构造函数吗?这是否需要一个比TH更强大的特殊预处理器?
解决方案
绝对可以使用模板Haskell来完成。几乎没有什么。但是我发现写模板Haskell代码很痛苦。
与GHC 7.4和 约束 扩展,您还可以抽象一部分:
data Some :: (* -> Constraint) -> * where
Some :: forall cls a. cls a => a -> Some cls
type Shape = Some Shape_
instance Shape_ Shape where
perimeter (Some a) = perimeter a
area (Some a) = area a
shape :: Shape_ a => a -> Shape
shape = Some
自动执行这些实例声明是另一回事,据我所知,只能做到这一点。
其他提示
在将方法添加到 Shape_
具有默认实现的类:
toShape :: a -> Shape
toShape = Shape
有关先前的艺术,请参阅 Exception
班级和 SomeException
数据类型。
不隶属于 StackOverflow