簡體   English   中英

使用Control.Lens的索引列表需要Monoid約束

[英]indexing list with Control.Lens requires Monoid constraint

以下代碼無法編譯:

{-# LANGUAGE TemplateHaskell #-}

import Control.Lens

data MyType = MyType Int
data Outer = Outer { _inners :: [ Inner ] }
data Inner = Inner { _val :: MyType }

$(makeLenses ''Outer)
$(makeLenses ''Inner)

i1 = Inner (MyType 1)
i2 = Inner (MyType 2)

o = Outer [i1, i2]

x = o ^. inners . ix 0 . val

給出這個錯誤

Toy.hs:17:23:
No instance for (Data.Monoid.Monoid MyType)
  arising from a use of `ix'
Possible fix:
  add an instance declaration for (Data.Monoid.Monoid MyType)
In the first argument of `(.)', namely `ix 0'
In the second argument of `(.)', namely `ix 0 . val'
In the second argument of `(^.)', namely `inners . ix 0 . val'

假設MyType不是一個幺半群是沒有意義的,我怎么能得到一個Lens(或Traversal,或者最合適的東西 - 我不確定區別)允許我訪問這個嵌套字段? 優選地具有讀取和更新的能力。

因為ix n可能會失敗(例如: n >= length list ),您需要一種干凈的失敗方法。 選擇干凈的失敗是mempty從元素Monoid 因此,立即出現的問題是,如果您的類型不能是Monoid,那么您希望此代碼如何失敗?

我建議你用^? 而不是^. ,從而重用名為MaybeMonoid

*Main> o ^? inners . ix 2 . val
Nothing
*Main> o ^? inners . ix 0 . val
Just (MyType 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM