haskell - 使用类型族的强制函数导致约束错误
问题描述
假设我有一些带有类型族的类型类:
class MyClass t where
data Fam t :: *
myfun :: t -> Fam t
instance MyClass Int where
newtype Fam Int = Triv Int
myfun = Triv
(与我的实际用例相比,简化了很多,以避免混乱。)
现在假设我想为任何可以嵌入到已经是类型类实例的东西中的类型提供默认实现。我想我可以写这样的东西:
class (MyClass (Embed t)) => Embeddable t where
type Embed t :: *
embed :: t -> Embed t
newtype MyNewtype t = MyConstructor t
instance (Embeddable t) => MyClass (MyNewtype t) where
newtype Fam (MyNewtype t) = MyFam (Fam (Embed t))
myfun (MyConstructor x) = MyFam (myfun . embed $ x)
myfunDef :: forall t. (Coercible (Fam (MyNewtype t)) (Fam t)) => t -> Fam t
myfunDef = coerce (myfun :: MyNewtype t -> Fam (MyNewtype t))
问题是这不能编译:
• Could not deduce: Embed t ~ t arising from a use of ‘coerce’
from the context: Coercible (Fam (MyNewtype t)) (Fam t)
bound by the type signature for:
myfunDef :: forall t.
Coercible (Fam (MyNewtype t)) (Fam t) =>
t -> Fam t
at src/Lib.hs:22:1-75
‘t’ is a rigid type variable bound by
the type signature for:
myfunDef :: forall t.
Coercible (Fam (MyNewtype t)) (Fam t) =>
t -> Fam t
at src/Lib.hs:22:1-75
• In the expression:
coerce (myfun :: MyNewtype t -> Fam (MyNewtype t))
In an equation for ‘myfunDef’:
myfunDef = coerce (myfun :: MyNewtype t -> Fam (MyNewtype t))
• Relevant bindings include
myfunDef :: t -> Fam t (bound at src/Lib.hs:23:1)
|
23 | myfunDef = coerce (myfun :: MyNewtype t -> Fam (MyNewtype t))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
我无法弄清楚为什么会出现此错误或如何解决它。
如果它已经编译,我打算像这样使用它:
instance Embeddable Bool where
type Embed Bool = Int
embed False = 0
embed True = 1
instance MyClass Bool where
newtype Fam Bool = BoolFam (Fam (Embed Bool))
myfun = myfunDef
显然,在这种情况下MyClass Bool
直接实现会相对简单,但想象一下它更复杂的情况。
解决方案
推荐阅读
- react-native - TextInput 值未更新
- javascript - 意外字符“#”
- gradle - Gradle 发布到 Github 包注册表返回 403 Forbidden
- session - 带有 CDI 的 JSF 2.3 中的会话固定和会话范围 Bean
- python - 自定义损失函数中没有梯度
- javascript - 自动谷歌登录 WebView React Native
- python - 在 Python 中的 DocuSign 中获取令牌
- ios - 旧 Apple 硬件上的 Cordova 和 Xcode 兼容性
- hybris - 如果数据模型不需要更新,如何减少 Hybris 构建时间?
- sql-server - SQL Server 克隆存储过程,包括授权