繁体   English   中英

在 haskell 中抓取类型 class 时,如何普遍量化 Reified Type Class 实例?

[英]how to universally quantify Reified Type Class instance when scraping your type class in haskell?

研究臭名昭著的博客文章scrap your type classes ,为了学习,但特别是为了理解类型 class 实例声明中forall的含义,如此处所述显式通用量化(forall)

除了在类型签名中,您还可以在实例声明中使用显式 forall:

实例forall a。 Eq a => Eq [a] 其中...

这通常是在我在 haskell 中完善我对forall的理解的背景下,其中我学会了如何小心它的 scope。

因此,为了明确起见,我一直在尝试为以下用例重现您的类型类方法的废料

data  DatumType a b = Datum a b deriving Show

instance forall a b . (Eq a, Eq b) => Eq (DatumType a b) where
  (==) (Datum x y) (Datum z e) =  x == z && y == e

将 Eq 重命名为 Same,即但声明为

data Same a = Same {
  (===) :: a -> a -> Bool
}

但是我被困在这里,因为我看不到如何使用 forall ab 编写实例

SameDatumTypeab :: ???
SameDatumTypeab =  Same {
 -- ???
}

任何人都可以帮忙吗? 这甚至可能吗?

没有什么是你不能想出一些反复试验的……

sameDatumTypeab :: ∀ a b . (Eq a, Eq b) => Same (DatumType a b)
sameDatumTypeab = Same {
   (===) = \(Datum x y) (Datum z e) -> x==z && y==e
 }

像往常一样,forall 是可选的(出现的变量在最外层隐含地进行了通用量化),即您可以简单地写

sameDatumTypeab :: (Eq a, Eq b) => Same (DatumType a b)
sameDatumTypeab = Same $ \(Datum x y) (Datum z e) -> x==z && y==e

但实际上这有点遗漏了 Scrap Your Classes 的要点,因为我现在正在使用Eq class 虽然我没有实例化它。 为了使其完全无类,我们还想转换(Eq a, Eq b)约束:

sameDatumTypeab :: Same a -> Same b -> Same (DatumType a b)
sameDatumTypeab (Same eqa) (Same eqb)
   = Same $ \(Datum x y) (Datum z e) -> eqa x z && eqb y e

FTR,typeclass实例也不需要显式量化

instance (Eq a, Eq b) => Eq (DatumType a b) where
  Datum x y == Datum z e = x == z && y == e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM