我正在为 Zoho REST API 编写一个客户端库,并且有一堆不同的记录类型,其中包含所有内容Maybe a
字段,即:
data Approval = Approval
{ apDelegate :: Maybe Bool
, apApprove :: Maybe Bool
, apReject :: Maybe Bool
, apResubmit :: Maybe Bool
} deriving (Eq, Show, Generic)
data ContactSpecialFields = ContactSpecialFields
{ csfCurrencySymbol :: Maybe Text -- $currency_symbol
, csfState :: Maybe Text -- $state
, csfProcessFlow :: Maybe Bool -- $process_flow
, csfApproved :: Maybe Bool -- $approved
, csfApproval :: Approval -- $approval
, csfEditable :: Maybe Bool -- $editable
} deriving (Eq, Show)
-- and so on
我需要一种方法来定义此类类型的“空”记录,例如:
emptyApproval :: Approval
emptyApproval = Approval
{ apDelegate = Nothing
, apApprove = Nothing
, apReject = Nothing
, apResubmit = Nothing
}
因此,我伸出手来GHC.Generics
并得到一些工作(这是有缺陷的!):
-- These parts seem logically correct to me...
class GEmptyZohoStructure f where
gEmptyZohoStructure :: f p
instance (GEmptyZohoStructure f, GEmptyZohoStructure g) => GEmptyZohoStructure (f :*: g) where
gEmptyZohoStructure = (gEmptyZohoStructure :: f p) :*: (gEmptyZohoStructure :: g p)
instance GEmptyZohoStructure Maybe where
gEmptyZohoStructure = Nothing
class EmptyZohoStructure a where
emptyZohoStructure :: a
default emptyZohoStructure :: (Generic a, (GEmptyZohoStructure (Rep a))) => a
emptyZohoStructure = GHC.Generics.to gEmptyZohoStructure
-- Whereas these parts are random type-class instances that I've written, just
-- to get the code to compile.
instance (GEmptyZohoStructure f) => GEmptyZohoStructure (M1 i t f) where
gEmptyZohoStructure = (gEmptyZohoStructure :: f p)
instance (GEmptyZohoStructure f) => GEmptyZohoStructure (K1 i (f p)) where
gEmptyZohoStructure = gEmptyZohoStructure
instance EmptyZohoStructure Approval
当代码编译时,以下(可以理解)会导致运行时堆栈溢出:
ghci> emptyZohoStructure :: Approval
*** Exception: stack overflow
我正在关注encode
教程位于https://www.stackage.org/haddock/lts-12.1/base-4.11.1.0/GHC-Generics.html#g:12 https://www.stackage.org/haddock/lts-12.1/base-4.11.1.0/GHC-Generics.html#g:12,由于参数被传递给encode
功能,它允许人们有机会打开M1
/ K1
构造函数并构建一些有意义的递归层次结构。我如何编写泛型M1
and K1
对于我的用例(通用函数实际上没有任何参数)?