写经典的镜头来记录类型家族?

时间:2018-08-15 08:50:57

标签: haskell lens type-families

Lenses and TypeFamiliesHow to derive instances for records with type-familiesHow to make lenses for records with type-families

有关

每次我都尝试使用类型家族来减少一些样板代码时,我都会将自己编程到一个角落。这是最新的一个-如何在下面给出的代码段中为RecordPoly f定义一个镜头?

{-# LANGUAGE TemplateHaskell, DeriveGeneric, MultiParamTypeClasses, FunctionalDependencies, UndecidableInstances, DataKinds #-}
module Try where

import Control.Lens

data PGInt
data PGText

data Selector = Haskell | DB


type family DBField (f :: Selector) hask db where
  DBField 'Haskell hask _ = hask
  DBField 'DB _ db = db

data RecordPoly f = RecordPoly
  { recFieldA :: !(DBField f Int PGInt)
  , recFieldB :: !(DBField f String PGText)
  }

class HasFieldA s a | s -> a where fieldA :: Lens' s a

instance HasFieldA (RecordPoly 'Haskell) Int where
  fieldA fctor (RecordPoly fa fb) = fmap (\x -> RecordPoly x fb) (fctor fa)

失败,并显示以下错误:

• Illegal instance declaration for ‘HasFieldA (RecordPoly f) a’
    The liberal coverage condition fails in class ‘HasFieldA’
      for functional dependency: ‘s -> a’
    Reason: lhs type ‘RecordPoly f’ does not determine rhs type ‘a’
    Un-determined variable: a
• In the instance declaration for ‘HasFieldA (RecordPoly f) a’

似乎唯一起作用的是以下内容:

instance HasFieldA (RecordPoly 'Haskell) Int where
  fieldA fctor (RecordPoly fa fb) = fmap (\x -> RecordPoly x fb) (fctor fa)

这是使其工作的唯一方法(从而导致一种新型样板爆炸)吗?此代码的类似多态版本如何工作,但与类型家族一起工作时却不起作用:

data RecordPoly fa fb = RecordPoly
  { recFieldA :: fa
  , recFieldB :: fb
  }

class HasFieldA s a | s -> a where fieldA :: Lens' s a

instance HasFieldA (RecordPoly fa fb) fa where
  fieldA fctor (RecordPoly fa fb) = fmap (\x -> RecordPoly x fb) (fctor fa)

1 个答案:

答案 0 :(得分:4)

最后想通了...

instance (fa ~ DBField f Int PGInt) => HasFieldA (RecordPoly f) fa where
  fieldA fctor (RecordPoly fa fb) = fmap (\x -> RecordPoly x fb) (fctor fa)