Joh*_*ith 9 haskell type-level-computation
我有一个具有一些相对不直观的约束的类实例。如果违反此约束,则会导致出现无法阅读的错误消息。我想做的是提供一个自定义类型错误,该错误以易于理解的方式解释了约束。我在这里看过,看上去似乎很接近我想要的。但是,我要生成的TypeError基于约束违例而不是实例声明。
这是我想要实现的示例代码:
data Foo (n :: Nat) = Foo
instance
(TypeError (Text "Missing KnownNat constraint"))
=> Eq (Foo n) where (==) = undefined
instance
(KnownNat n)
=> Eq (Foo n) where (==) _ _ = True
Run Code Online (Sandbox Code Playgroud)
我特别不需要两个实例声明。如果还有其他方法可以做到,我也很好。
小智 0
虽然以下方法并不适用于所有限制。如果您的约束对有限数量的类型进行操作,您可以执行如下操作:
class Bar a where
baz :: a -> a
data Foo (n :: Nat) = Foo deriving Show
instance {-# OVERLAPS #-} Bar (Foo 0) where
baz = id
instance {-# OVERLAPS #-} Bar (Foo 1) where
baz = id
instance {-# OVERLAPPABLE #-} (TypeError (Text "N is greater then 1")) => Bar (Foo a) where
baz = undefined
r1 = baz (Foo :: Foo 0) -- succeeds
r2 = baz (Foo :: Foo 1) -- succeeds
r3 = baz (Foo :: Foo 2) -- fails with custom type error
Run Code Online (Sandbox Code Playgroud)
我将保持这个问题的开放性,直到有人给出一个通用的解决方案或告诉我们这是不可能的,并给出一些好的解释。