为什么没有解析此HasField实例?

时间:2017-08-13 10:04:14

标签: haskell records

我正在使用 GHC 8.2.1 。我有以下模块:

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Moat (Moat,moat) where

import GHC.Records (HasField(..))

newtype Moat r = Moat r

moat :: r -> Moat r
moat = Moat

instance HasField s r v => HasField s (Moat r) v where
    getField (Moat r) = getField @s r

另一个:

module Foo (Foo(..)) where

data Foo a = Foo { getDims :: (Int, Int), getData :: [a] }

我的问题是,当我导入了两个模块时,我尝试执行以下操作:

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE DataKinds #-}
import Moat
import Foo
import GHC.Records

oops :: (Int,Int)
oops = getField @"getDims" (moat (Foo (5,5) ['c']))

我收到此错误:

No instance for (HasField "getDims" (Moat (Foo Char)) (Int, Int))
       arising from a use of ‘getField’

为什么HasField实例未被解析?

1 个答案:

答案 0 :(得分:4)

通过在定义{-# LANGUAGE PolyKinds #-}实例的Moat模块中启用HasField来解决问题。

我认为这与多边形HasField类型类有关:

λ :info HasField
class HasField k (x :: k) r a | x r -> a where
    getField :: r -> a

这允许我们像这样定义HasField个实例,其中字段选择器是非Symbol类型:

import GHC.Records
data A = A B
data B = B deriving Show
instance HasField B A B where
    getField (A b) = b

在ghci:

λ> getField @B (A B)
B