2017-12-29 41 views
7

を壊し、私は非常に無実に見えるコードTypeFamiliesまたはGADTsが突然有効なコード

data Config = Config 
    { cInts :: [Int] 
    , cStrings :: [String] } 

instance Semigroup Config where 
    c1 <> c2 = Config 
     { cInts = andCombiner cInts 
     , cStrings = andCombiner cStrings } 
     where 
     andCombiner field = field c1 <> field c2 

を持っていることは、コンパイルし、正常に動作します。私はTypeFamiliesGADTs拡張子を追加する場合は、私は非常に奇妙なエラーが表示されます。

.../Main.hs:19:22: error: 
    • Couldn't match type ‘Int’ with ‘[Char]’ 
     Expected type: [String] 
     Actual type: [Int] 
    • In the ‘cStrings’ field of a record 
     In the expression: 
     Config {cInts = andCombiner cInts, cStrings = andCombiner cStrings} 
     In an equation for ‘<>’: 
      c1 <> c2 
      = Config 
       {cInts = andCombiner cInts, cStrings = andCombiner cStrings} 
      where 
       andCombiner field = field c1 <> field c2 
    | 
19 |   , cStrings = andCombiner cStrings } 
    |      ^^^^^^^^^^^^^^^^^^^^ 

.../Main.hs:19:34: error: 
    • Couldn't match type ‘[Char]’ with ‘Int’ 
     Expected type: Config -> [Int] 
     Actual type: Config -> [String] 
    • In the first argument of ‘andCombiner’, namely ‘cStrings’ 
     In the ‘cStrings’ field of a record 
     In the expression: 
     Config {cInts = andCombiner cInts, cStrings = andCombiner cStrings} 
    | 
19 |   , cStrings = andCombiner cStrings } 
    |         ^^^^^^^^ 

このコンパイラエラーの原因になることができますか?

答えて

10

これはのため、-XGADTs-XTypeFamiliesのことを示しています。 (私はを行うことがないをすることをお勧めします、または-XNoMonoLocalBindsをオンにすることで)あなたはandCombinerに型シグネチャを追加することによって、再びコンパイルするようにコードを取得することができます:

instance Semigroup Config where 
    c1 <> c2 = Config 
     { cInts = andCombiner cInts 
     , cStrings = andCombiner cStrings } 
     where 
     andCombiner :: Semigroup a => (Config -> a) -> a 
     andCombiner field = field c1 <> field c2 

私がリンクしたGHCのドキュメントから用語を使用しますandCombinerは、閉じられていないかインポートされていないc1c2と記載されているため、完全に一般化されていません。

+4

'-XNoMonoLocalBinds' *をオフにして、' -XNoMonoLocalBinds'とすることを意味しますか? – HTNW

+0

@HTNWはい、ありがとうございます! – Alec

関連する問題