使用Control.Lens编写镜头,必须调用中间函数

时间:2013-09-02 21:22:00

标签: haskell functional-programming lenses

假设我有以下内容:

{-# 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更改第三个?我似乎应该为此制作一个新镜头。我认为我应该用bookstitle组成map!!镜头,即books . (!! 2) . title -- or books . map . title 或{{1}}。

{{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允许您处理列表中的每个元素。如果要生成列表中的一个元素,则使用elementInt表示处理的索引。

> 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"}]}

希望有所帮助。