我大概想是這樣的:擴展記錄(我認爲)
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文檔中有點迷茫,所以我只想要一些示例代碼(或者一些示例代碼的鏈接),它們大致可以實現我正在尋找的內容。