【发布时间】:2017-06-21 04:02:14
【问题描述】:
我大致想要的是这样的:
data A = ...
data B = ...
data C = ...
class HasA t where
getA :: t -> A
class HasB t where
getB :: t -> B
class HasC t where
getC :: t -> C
所以我可以这样做(伪代码如下):
a :: A
b :: B
x = mkRecord { elemA a, elemB b }
y = mkRecord { elemB b, elemA a }
-- type of `x` == type of `y`
当然,只有适当的get 函数才能工作,在上述情况下是getA 和getB。
我也想要以下功能
slice :: Subset a b => a -> b
slice x = -- just remove the bits of x that aren't in type b.
add :: e -> a -> a ++ e
add e x = -- add an element to the "record" (compile error if it's already there)
我觉得这不是一个新问题,因此可能已经存在解决方案。请注意,我不要求解决方案是可扩展的,我需要处理的类型数量是有限且已知的,但当然可扩展的也不会受到影响。
我发现了几个似乎在我正在寻找的领域中的包,即HList 和extensible(也许可扩展更好,因为我希望我的记录无序)。我在 Hackage 文档中有点迷失,所以我只想要一些示例代码(或一些示例代码的链接),它们大致实现了我正在寻找的内容。
【问题讨论】:
标签: haskell