假设我有以下内容:
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens
data Book = Book {
_author :: String,
_title :: String
} deriving (Show)
makeLenses ''Book
data Location = Location {
_city :: String,
_state :: String
} deriving (Show)
makeLenses ''Location
data Library = Library {
_location :: Location,
_books :: [Book]
} deriving (Show)
makeLenses ''Library
lib :: Library
lib = Library (Location "Baltimore" "MD") [Book "Plato" "Republic", Book "Aristotle" "Ethics"]
我正在尝试通过组合镜头来了解通过多层覆盖的各种方法。我知道如何进行这些操作:
-- returns "Baltimore"
lib ^. location . city
-- returns a copy of lib with the city replaced
set (location . city) "Silver Spring" lib
但如果我想改变书名怎么办?也许我想使用map
更改它们,或者我只想使用!! 2
更改第三个?我似乎应该为此制作一个新镜头。我认为我应该用books
或title
组成map
和!!
镜头,即books . (!! 2) . title
-- or
books . map . title
或{{1}}。
{{1}}
我该怎么做?
答案 0 :(得分:8)
muhmuhten是正确的,您应该阅读traversals包中的lens。
> over (books . traverse . title) (++" hi") lib
Library {_location = Location {_city = "Baltimore", _state = "MD"}, _books = [Book {_author = "Plato", _title = "Republic hi"},Book {_author = "Aristotle", _title = "Ethics hi"}]}
traverse
允许您处理列表中的每个元素。如果要生成列表中的一个元素,则使用element
,Int
表示处理的索引。
> over (books . element 0 . title) (++" hi") lib
Library {_location = Location {_city = "Baltimore", _state = "MD"}, _books = [Book {_author = "Plato", _title = "Republic hi"},Book {_author = "Aristotle", _title = "Ethics"}]}
希望有所帮助。