也许是动态调度、智能构造函数、Template Haskell?

发布于 2024-12-10 11:33:18 字数 691 浏览 4 评论 0原文

我正在查看 HaskellWiki >;存在类型 # 动态调度机制

我在想,Template 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)

这在 Template Haskell 中完成了吗?这可以在TH 完成吗?是否可以在普通的 Haskell 中完成类似的事情,而无需手动编写所有智能构造函数?这是否需要一个比 TH 更强大的特殊预处理器?

I'm looking at HaskellWiki > Existential type # Dynamic dispatch mechanism.

And I'm thinking, there should be a way in Template Haskell to take this part:

class Shape_ a where
    ...

type Radius = Double
data Circle = Circle Radius

instance Shape_ Circle where
    ...

and automatically derive this part:

-- 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)

Has this been done in Template Haskell? Can this be done in TH? Can something similar be done in plain old Haskell without having to write out all of the smart constructors by hand? Would this require a special pre-processor that is more powerful than TH?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

_蜘蛛 2024-12-17 11:33:18

这绝对可以使用 Template Haskell 来完成。很少有做不到的。但我发现编写 Template Haskell 代码相当痛苦。

使用 GHC 7.4 和 ConstraintKinds 扩展,您还可以抽象它的一部分:

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

自动化这些实例声明是 TH 的另一件事,据我所知,只有 TH 可以做到。

It can most definitely be done with Template Haskell. There's very little which can't. But I find writing Template Haskell code to be rather painful.

With GHC 7.4 and the ConstraintKinds extension, you can also abstract part of it:

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

Automating those instance declarations is another thing TH, and to the best of my knowledge only TH, can do.

宛菡 2024-12-17 11:33:18

如何向具有默认实现的 Shape_ 类添加一个方法:

toShape :: a -> Shape
toShape = Shape

有关现有技术,请参阅 Exception 类和 SomeException 数据类型。

What about adding a method to the Shape_ class with a default implementation:

toShape :: a -> Shape
toShape = Shape

For prior art, see the Exception class and SomeException datatype.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文