首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GHC.Generics示例不工作

GHC.Generics示例不工作
EN

Stack Overflow用户
提问于 2015-03-02 04:21:14
回答 1查看 159关注 0票数 3

我试图让GHC.Generics中描述的一个通用二进制编码类的示例实现正常工作,但是当我试图编译它时,会出现一个错误。

代码语言:javascript
复制
import GHC.Generics

class Encode' f where
  encode' :: f p -> [Bool]

instance Encode' V1 where
  encode' x = undefined

instance Encode' U1 where
  encode' U1 = []

instance (Encode' f, Encode' g) => Encode' (f :+: g) where
  encode' (L1 x) = False : encode' x
  encode' (R1 x) = True  : encode' x

instance (Encode' f, Encode' g) => Encode' (f :*: g) where
  encode' (x :*: y) = encode' x ++ encode' y

instance (Encode c) => Encode' (K1 i c) where
  encode' (K1 x) = encode x

instance (Encode' f) => Encode' (M1 i t f) where
  encode' (M1 x) = encode' x

class Encode a where
  encode :: a -> [Bool]
  default encode :: (Generic a) => a -> [Bool]
  encode x = encode' (from x)

GHC抱怨:

代码语言:javascript
复制
Could not deduce (Encode' (Rep a)) arising from a use of ‘encode'’
from the context (Encode a)
  bound by the class declaration for ‘Encode’
  ...
or from (Generic a)
  bound by the type signature for encode :: Generic a => a -> [Bool]
  ...
In the expression: encode' (from x)
In an equation for ‘encode’: encode x = encode' (from x)

我遗漏了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-02 04:34:20

不是所有的Generic都可以由encode'编码。只有那些同时具有Generic和表示的事物,具有Encode'实例的Rep a才能被泛型encode'编码。编译器不知道(也不知道)没有GenericRep不被Encode'实例覆盖的东西。Generic实例的作者可以为他们的Rep使用一个甚至还不存在的类型。

您需要将请求的Encode' (Rep a)约束添加到default encode的上下文中。

代码语言:javascript
复制
default encode :: (Generic a, Encode' (Rep a)) => a -> [Bool]
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28802666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档