无需重写所有代码并手动插入 Maybes 即可获得相同的结果
为了避免对记录类型的侵入性更改,我们可以通过分析其结构来处理从记录派生的另一种类型,这需要相对高级的泛型和类型级编程。这个答案使用generics-sop包。
一些必需的编译指示和导入:
{-# LANGUAGE DataKinds, TypeFamilies, FlexibleInstances, UndecidableInstances,
ScopedTypeVariables, TypeApplications, TypeOperators,
DeriveGeneric, StandaloneDeriving, MultiParamTypeClasses,
FunctionalDependencies, AllowAmbiguousTypes, FlexibleContexts #-}
import Data.Kind (Type)
import Data.Type.Equality (type (==))
import GHC.TypeLits
import qualified GHC.Generics as GHC
import Generics.SOP -- from package "generics-sop"
import qualified Generics.SOP.Type.Metadata as M
这种新类型表示从记录派生的字段值的n 元乘积f,每个值都包装在一个仿函数中。ns字段名称的类型级别列表保存为幻像类型变量:
newtype Wrapped f (ns :: [Symbol]) (xs :: [Type]) = Wrapped { unwrap :: NP f xs }
deriving instance All (Generics.SOP.Compose Show f) xs => Show (Wrapped f ns xs)
type family FieldNamesOf (a :: M.DatatypeInfo) :: [Symbol] where
FieldNamesOf ('M.ADT moduleName datatypeName '[ 'M.Record constructorName fields ]) =
ExtractFieldNames fields
type family ExtractFieldNames (a :: [M.FieldInfo]) :: [Symbol] where
ExtractFieldNames '[] = '[]
ExtractFieldNames (('M.FieldInfo n) ': xs) = n ': ExtractFieldNames xs
fromRecord :: forall r ns xs. (IsProductType r xs,
HasDatatypeInfo r,
FieldNamesOf (DatatypeInfoOf r) ~ ns)
=> r
-> Wrapped I ns xs
fromRecord r = let (SOP (Z np)) = from r in Wrapped np
toRecord :: forall r ns xs. (IsProductType r xs,
HasDatatypeInfo r,
FieldNamesOf (DatatypeInfoOf r) ~ ns)
=> Wrapped I ns xs
-> r
toRecord (Wrapped np) = to (SOP (Z np))
如果我们不需要保留字段名称,那么 newtype 就变得多余了,最好直接使用 n 元乘积NP ,使用generics-sop 提供的丰富函数集来操作它。
但是如果我们确实想保持按名称选择字段的能力,那么我们需要在 newtype 上定义一个函数,由一对 typeclasses 支持:
getWrappedField :: forall n f ns xs x. HasField ns n xs x => Wrapped f ns xs -> f x
getWrappedField (Wrapped np) = getHasField @ns @n np
class HasField (ns :: [Symbol]) (n :: Symbol)
(xs :: [Type]) (x :: Type) | ns n xs -> x where
getHasField :: NP f xs -> f x
instance ((e == n) ~ flag, HasField' flag (e : ns) n xs x) => HasField (e : ns) n xs x where
getHasField = getHasField' @flag @(e : ns) @n
class HasField' (flag :: Bool)
(ns :: [Symbol]) (n :: Symbol)
(xs :: [Type]) (x :: Type) | ns n xs -> x where
getHasField' :: NP f xs -> f x
instance HasField' True (n : ns) n (x : xs) x where
getHasField' (v :* _) = v
instance HasField ns n xs x => HasField' False (nz : ns) n (xz : xs) x where
getHasField' (_ :* rest) = getHasField @ns @n rest
鉴于此示例记录派生了必要的 支持 类型类:
data Person = Person { name :: String, age :: Int } deriving (Show, GHC.Generic)
instance Generic Person
instance HasDatatypeInfo Person
我们可以构造它的广义表示(所有字段最初都包含在恒等函子I中),然后获取其中一个字段,如下所示:
ghci> getWrappedField @"age" (fromRecord (Person "Jimmy" 25))
I 25
字段的名称作为类型级别传递Symbol,使用类型 application。