如何强制约束?

nic*_*las 5 haskell deriving derivingvia

在 Haskell 中是否有任何强制约束的机制(除了unsafeCoerce我希望有效)?

{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE StandaloneKindSignatures #-}
{-# LANGUAGE TypeApplications #-}
module CatAdjonctionsSOQuestion where

import Data.Proxy
import Data.Tagged
import Unsafe.Coerce

newtype K a ph = K {unK :: a} -- I would want c a => c ((K a) i) for any c :: Constraints

-- I could do any possible instance by hand
deriving via a instance Semigroup a => Semigroup ((K a) i)

-- I want them all
-- deriving via a instance c ((K a) i) -- Instance head is not headed by a class: c (K a i)

data Exists c where
  Exists :: c a => a -> Exists c

data ExistsKai c i where
  ExistsKai :: c ((K a) i) => Proxy a -> ExistsKai c i

ok :: forall x c i. (forall x. (forall a. c a => a -> x) -> x) -> (forall a. c ((K a) i) => Tagged a x) -> x
ok s k =
  let e = (s Exists :: Exists c)
   in let f = unsafeCoerce e :: ExistsKai c i
       in case f of (ExistsKai (Proxy :: Proxy a)) -> unTagged (k @a)
Run Code Online (Sandbox Code Playgroud)

dfe*_*uer 3

稍微修改一下以进行类型检查,您要求

newtype K a ph = K {unK :: a}
-- I would want c a => c ((K a) i)
-- for any c :: Type -> Constraint
Run Code Online (Sandbox Code Playgroud)

无论现在还是永远,你绝对无法得到它,因为它是无效的。考虑

(~) Bool :: Type -> Constraint
Run Code Online (Sandbox Code Playgroud)

现在(~) Bool Bool成立,但你永远无法实现(~) Bool (K Bool i)

如果没有平等约束呢?好吧,我也可以使用莱布尼茨等式来做到这一点:

class Bar a where
  isBool :: f a -> f Bool

instance Bar Bool where
  isBool = id
Run Code Online (Sandbox Code Playgroud)

但没办法写instance Bar (K Bool i)isBool没有触底。