【发布时间】:2016-04-11 09:13:57
【问题描述】:
我正在按照教程为来自hackage documentation 的GHC.Generics 的数据类型构建通用“编码”函数。我已将代码复制粘贴到(并包括)“包装器和通用默认值”部分,但出现以下错误:
Main.hs:35:14:
Could not deduce (Encode' (Rep a)) arising from a use of ‘encode'’
from the context (Encode a)
bound by the class declaration for ‘Encode’
at Main.hs:(32,1)-(35,29)
or from (Generic a)
bound by the type signature for encode :: Generic a => a -> [Bool]
at Main.hs:33:13-23
In the expression: encode' (from x)
In an equation for ‘encode’: encode x = encode' (from x)
Failed, modules loaded: none.
我复制的代码如下:
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveAnyClass #-}
module Main where
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)
我认为问题在于最终的类声明 (class Encode a where ...)。我已经通过添加一个额外的约束来修复它,以获得这个:
class Encode a where
encode :: a -> [Bool]
default encode :: (Generic a, Encode' (Rep a)) => a -> [Bool]
encode x = encode' (from x)
这似乎像宣传的那样工作——我可以声明新的数据类型并使用DeriveAnyClass 和deriving 使它们可编码。但是,我不确定为什么我的修复是必要的。我的问题是:
- 文档有误吗?
-
Encode' (Rep a)约束是否应该出现在有关 hackage 的示例代码中? - 如果没有,我应该添加什么才能使代码正常工作?
【问题讨论】: