现在 RecSummaryFuns a 应该具有与 a 相同的“字段名称”(构造函数参数)
此答案使用red-black-record构造与原始记录具有相同字段名称的“通用记录” Foo。首先我们必须自动派生一些支持的类型类:
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeApplications #-}
{-# OPTIONS_GHC -Wno-partial-type-signatures #-} -- hide some scary types
import Data.RBR (FromRecord (..), Record, ToRecord (..), fromNP, insert, toNP, unit)
import Data.SOP (I (I), NP) -- from sop-core
import Data.SOP.NP (liftA2_NP, liftA_NP) -- useful functions for n-ary products
import GHC.Generics
data Foo
= Foo
{ v1 :: Int,
v2 :: Double
}
deriving (Show, Generic, FromRecord, ToRecord)
现在我们可以定义一个通用记录的值,它的字段将保存函数。遗憾的是,我们不能使用通常的记录语法:
newtype Func a = Func ([a] -> a) -- helper newtype encapsulating the function
type FooFunc = Record Func (RecordCode Foo) -- wrap every field in Func
exampleFunc :: FooFunc
exampleFunc =
insert @"v1" (Func head) -- field names give with TypeApplications
. insert @"v2" (Func last) -- same order as in the original record
$ unit -- unit is the empty record
下一步是在sop-core提供的n-ary product数据类型的帮助下定义这个通用的 apply 函数:
applyFunc :: _ => Record Func _ -> [r] -> r
applyFunc func foos =
let foos_NP :: [NP I _] -- a list of n-ary products. I is an identity functor
foos_NP = toNP . toRecord <$> foos
listfoos_NP :: [NP [] _] -- turn every component into a singleton list
listfoos_NP = liftA_NP (\(I x) -> [x]) <$> foos_NP
listfoo_NP :: NP [] _ -- a single n-ary product where each component is a list
listfoo_NP = mconcat listfoos_NP
func_NP :: NP Func _ -- turn the function record into a n-ary prod
func_NP = toNP func
resultFoo_NP_I :: NP I _ -- apply the functions to each list component
resultFoo_NP_I = liftA2_NP (\(Func f) vs -> I (f vs)) func_NP listfoo_NP
in fromRecord . fromNP $ resultFoo_NP_I -- go back to the nominal record Foo
把它们放在一起:
main :: IO ()
main =
print $
applyFunc exampleFunc [Foo 0 0.0, Foo 1 1.0]
-- result: Foo {v1 = 0, v2 = 1.0}
此解决方案的可能缺点是编译时间较长,而且将 list-of- Foos 转换为Foo内部的 -with-list-fieldsapplyFunc可能对于长列表效率低下。
我们可以抛弃red-black-record ——我们只使用它来保存通用记录中的字段名称——并直接依赖sop-core / generics-sop;在这种情况下,字段名称的处理方式会有所不同——或者我们可以简单地依赖位置匹配。