[英]Avoid `undefined` when using `TypeError` in type-class constraint
我有一个像这样的类型类实例:
instance {-# OVERLAPPABLE #-} (TypeError ( 'Text "Some error")) => SomeClass x where
someMethod = undefined
此实例存在于其他(有效)实例的末尾。 这个想法是让编译器在用户编写不符合这些有效实例的类型时抛出类型错误。 实例约束中的TypeError
实现了这一点,但这也迫使我用undefined
填充方法,这感觉就像一个 hack。
有没有办法避免这种情况? 还是做得更好?
我能做到的最好的就是这个。 本质上,我定义了一个TypeErr
类型族,代表标准TypeError
约束和提供所需见证的附加Impossible
约束。 Impossible
总是无法解决为约束,但无论如何都会首先触发类型错误。
{-# LANGUAGE DataKinds, UndecidableInstances, TypeFamilies #-}
import GHC.TypeLits (
ErrorMessage (Text),
TypeError,
)
class Impossible where
impossible :: a
type family TypeErr t where
TypeErr t = (TypeError t, Impossible)
-- Dummy example
class SomeClass x where
someMethod :: x -> Maybe x
instance {-# OVERLAPPABLE #-} (TypeErr ( 'Text "Some error"))
=> SomeClass x where
someMethod = impossible
main :: IO ()
main = print (someMethod True)
{-
<source>:19:15: error:
* Some error
* In the first argument of `print', namely `(someMethod True)'
In the expression: print (someMethod True)
In an equation for `main': main = print (someMethod True)
-}
我们在trivial-constraint
包中有Disallowed
类。 它提供了nope
伪方法,这是undefined
的一个版本,只能在不可能的上下文中使用(并且可以通过“使用” unboxed来证明这一点,这是标准undefined
无法做到的)。
instance {-# OVERLAPPABLE #-} (Disallowed "fallback for `SomeClass`")
=> SomeClass x where
someMethod = nope
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.