[英]How to write an instance of Control.Lens.AT
我有一個數據結構,可以理解為類似於Data.Map
,因為它將一種類型的鍵映射到另一種類型的值。 我想為這種類型編寫一個Control.Lens.At
實例,但我似乎無法滿足所有要求。
給定具有lookup
, insert
, update
和delete
Struct kv
,我必須做什么才能使instance At (Struct kv)
工作?
at
方法應該為給定索引返回一個索引鏡頭作為輸入結構,其行為如下:
Nothing
,否則返回結構中鍵的值。 Nothing
,則從結構中刪除鍵,否則將其設置(或者如果它不存在則創建它)到Just
的值。 at
。 這導致以下代碼滿足您的要求:
instance At (Struct k v) where
at key = ilens getter setter
where getter = (key, lookup key)
setter s Nothing = delete key s
setter s (Just newValue) = insert key newValue s
我用
lens
構造一個透鏡
ilens
從吸氣和一個setter構建一個索引透鏡。 我還假設您的函數具有以下類型:
lookup :: k -> Struct k v -> Maybe v
delete :: k -> Struct k v -> Struct k v
insert :: k -> v -> Struct k v -> Struct k v
-- Insert should override the key when it's already there
您仍然需要定義IxValue
和Index
類型族實例:
type instance IxValue (Struct k v) = v -- A (Struct k v) contains values of type v
type instance Index (Struct k v) = k -- A (Struct k v) has keys of type k.
編輯 :實際上,必須返回一個索引鏡頭,而不僅僅是一個鏡頭。 我也混淆了setter的參數順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.