繁体   English   中英

在类型类约束中使用 `TypeError` 时避免 `undefined`

[英]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.

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