我正在为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
我正在遵循https://www.stackage.org/haddock/lts-12.1/base-4.11.1.0/GHC-Generics.html#g:12上的encode
教程,在该教程中,由于将参数传递给了encode
函数,它使人们有机会解开M1
/ K1
构造函数,并构建一些有意义的递归层次结构。 如何为用例(其中泛型函数实际上没有任何参数)编写M1
和K1
的泛型?
答案 0 :(得分:3)
在泛型的类型类中定义GEmptyZohoStructure Maybe
毫无意义。
class G f where
gempty' :: f p
instance (G f, G g) => G ( f :*: g) where
gempty' = gempty' :*: gempty'
instance G c => G (D1 x c) where
gempty' = M1 gempty'
instance G s => G (C1 x s) where
gempty' = M1 gempty'
instance E t => G (S1 m (Rec0 t)) where -- the key instance
gempty' = M1 (K1 gempty)
class E a where
gempty :: a
default gempty :: (Generic a, G (Rep a)) => a
gempty = to gempty'
instance E (Maybe a) where
gempty = Nothing
之后,您可以定义由Maybe值组成的任何产品类型。