[英]Haskell reflection: does record have field?
GHC 泛型工具可讓您檢查構造函數名稱,但字段名稱呢?
假設我有一個數據類型
data Foo
= F {f :: Int}
| OO {oo :: String}
| Foo {f :: Int, oo :: String}
我有以下數據
aFoo :: Foo
我可以寫這樣的東西:
ooMay :: Foo -> Maybe String
ooMay f@(Foo {}) = Just (oo f)
ooMay f@(OO {}) = Just (oo f)
ooMay f@(F {}) = Nothing
通過我知道可以安全使用的構造函數保護訪問器oo
。
有沒有辦法用泛型來寫這個? 像fieldMay
這樣的fieldMay
存在嗎?
ooMay :: Foo -> Maybe String
ooMay f = fieldMay "oo" f
是的,這是可行的。 字段名稱作為M1
類型構造函數的參數( Meta
參數)寫入Rep
。 Haddock 掩蓋了M1
,示例Generic
基於類忽略了其中的信息,但現在我們需要它。
只是為了讓我們知道我們在處理什么:
ghci> :kind! Rep Foo
Rep Foo :: * -> *
= D1
('MetaData "Foo" "Ghci1" "interactive" 'False)
(C1
('MetaCons "F" 'PrefixI 'True)
(S1
('MetaSel
('Just "f") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy)
(Rec0 Int))
:+: (C1
('MetaCons "OO" 'PrefixI 'True)
(S1
('MetaSel
('Just "oo")
'NoSourceUnpackedness
'NoSourceStrictness
'DecidedLazy)
(Rec0 String))
:+: C1
('MetaCons "Foo" 'PrefixI 'True)
(S1
('MetaSel
('Just "f") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy)
(Rec0 Int)
:*: S1
('MetaSel
('Just "oo")
'NoSourceUnpackedness
'NoSourceStrictness
'DecidedLazy)
(Rec0 String))))
所以我們基本上只是搜索S1
並選擇具有正確名稱的那個。 為簡單起見,讓我們先看看那些具有正確類型的。
class GFieldMay rep a where
gFieldMay :: String -> rep p -> Maybe a
-- fields of the right type might match the name
instance {-# OVERLAPS #-} Selector s => GFieldMay (M1 S s (K1 i a)) a where
gFieldMay name m@(M1 (K1 x))
| name == selName m = Just x
| otherwise = Nothing
-- any other fields must be pruned (no deep search)
instance {-# OVERLAPPING #-} GFieldMay (M1 S s f) a where
gFieldMay _ _ = Nothing
-- drill through any other metadata
instance {-# OVERLAPPABLE #-} GFieldMay f a => GFieldMay (M1 i m f) a where
gFieldMay name (M1 x) = gFieldMay name x
-- search both sides of products
instance (GFieldMay l a, GFieldMay r a) => GFieldMay (l :*: r) a where
gFieldMay name (l :*: r) = gFieldMay name l <|> gFieldMay name r
-- search the given side of sums
instance (GFieldMay l a, GFieldMay r a) => GFieldMay (l :+: r) a where
gFieldMay name (L1 x) = gFieldMay name x
gFieldMay name (R1 x) = gFieldMay name x
就是這樣
fieldMay :: (Generic a, GFieldMay (Rep a) f) => String -> a -> Maybe f
fieldMay name = gFieldMay name . from
達達!
main = putStr $ unlines $
[ show x ++ ": " ++ show (fieldMay "oo" x :: Maybe String)
| x <- [F 42, OO "5", Foo 42 "5"]]
-- F {f = 42}: Nothing
-- OO {oo = "5"}: Just "5"
-- Foo {f = 42, oo = "5"}: Just "5"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.