gpt4 book ai didi

haskell - 如何强制约束?

转载 作者:行者123 更新时间:2023-12-04 11:29:51 24 4
gpt4 key购买 nike

在 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)

最佳答案

稍加修改以进行检查,您要求

newtype K a ph = K {unK :: a}
-- I would want c a => c ((K a) i)
-- for any c :: Type -> Constraint
你绝对不能得到它,现在或永远,因为它是无效的。考虑
(~) Bool :: Type -> Constraint
现在 (~) Bool Bool持有,但你永远无法达到 (~) Bool (K Bool i) .
没有等式约束呢?嗯,我也可以这样做,使用莱布尼茨等式:
class Bar a where
isBool :: f a -> f Bool

instance Bar Bool where
isBool = id
但是没有办法写 instance Bar (K Bool i)谁的 isBool没有触底。

关于haskell - 如何强制约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67557365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com