简体   繁体   English

制定一个可能的约束方程式

[英]Making a constraint of Maybe a where Eq a

How can I constrain to Maybe a where Eq a? 我怎样才能约束到Eq a? It needs to be of kind * -> Constraint 它需要是善良的 - >>约束

What I tried: 我尝试了什么:

class (a ~ Maybe b, Eq b) => K a where
instance (a ~ Maybe b, Eq b) => K a where

Error: 错误:

Not in scope: type variable ‘b’

Example Usage: 用法示例:

data Test c = forall a. (c a) => Test a
r :: Test K -> Maybe Bool
r (Test o) = (==) <$> o <*> o -- I need GHC to infer that o is Maybe Eq

Cases that work: 有效的案例:

pp :: Test ((~) String) -> String
pp (Test o) = o ++ "X" -- GHC infers that o is a string

hh :: Test Eq -> Bool
hh (Test o) = o == o -- GHC infers that o is Eq

Generic answer here: Is there a general way to apply constraints to a type application? 这里的通用答案: 是否有一种将约束应用于类型应用程序的一般方法?

The following compiles on my machine. 以下编译在我的机器上。 No idea how sensible it is. 不知道它是多么明智。

{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ConstraintKinds #-}
class (Eq (UnMaybe a), a ~ Maybe (UnMaybe a)) => EqMaybe a where
    type UnMaybe a

instance Eq a => EqMaybe (Maybe a) where
    type UnMaybe (Maybe a) = a

data Test c = forall a. c a => Test a
r :: Test EqMaybe -> Maybe Bool
r (Test o) = (==) <$> o <*> o
f :: Test Eq -> Test EqMaybe
f (Test o) = Test (Just o)

This is a known issue . 这是一个已知问题 GHC is choking up because you have introduced a new type variable b not mentioned anywhere else in the instance head. GHC正在窒息,因为你已经引入了一个新的类型变量b ,在实例头中的其他任何地方都没有提到。 One workaround is to use type families and constraint kinds. 一种解决方法是使用类型族和约束种类。

{-# LANGUAGE ConstraintKinds, TypeFamilies, UndecideableInstances, 
             UndecideableSuperclasses, FlexibleInstances
  #-}

import GHC.Exts (Constraint)
import GHC.Prim (Any)

type family MaybeEq x :: Constraint where
  MaybeEq (Maybe a) = Eq a
  MaybeEq _         = Any    -- A good "unsatisfiable" constraint

class MaybeEq a => K a where
instance MaybeEq a => K a where

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

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