2016-04-11 10 views
4

私は、GHC.Genericshackage documentationからのデータ型の汎用 "エンコード"機能を構築するためのチュートリアルに従っています。私はコピー&ペーストする(を含む)までのコードセクションでは、「ラッパーとジェネリックデフォルト」をしましたが、私は次のエラーを取得する:Haskell/GHC Genericsドキュメンテーションの例でtypeclassの制約がありませんか?

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) 

これは宣伝として動作しているようです - 私は、新しいデータ型を宣言し、それらをDeriveAnyClassderivingでエンコード可能にすることができます。しかし、なぜ私の修正が必要なのかは分かりません。私の質問は次のとおりです。

  • ドキュメントが間違っていますか?
  • Encode' (Rep a)の制約がハックのサンプルコードに存在する必要がありますか?
  • そうでない場合は、コードを動作させるために何を追加する必要がありますか?

答えて

4

はい、私はドキュメントが間違っていると思います。制約が必要です。

+0

Cool!誰と話すのですか/どこで修正するのですか? – statusfailed

+1

@statusfailed実際には、http://downloads.haskell.org/~ghc/master/libraries/html/base/GHC-Generics.html#g:13(Ben Gamariのおかげで)の修正済みです。 – kosmikus

関連する問題