Control.Lens
重載了遍歷支持:
import Control.Lens
-- Convert to list:
(3, 4, 5)^..each -- [3, 4, 5]
(1, 2)^..each -- [1, 2]
-- modify elements:
(4, 16, 32)& each %~ \x -> x * 2 -- (8, 32, 64)
(1, 2)& each %~ (+1) -- (2, 3)
-- operator notation for common modifications (see Control.Lens.Operators):
(1, 2, 3)& each +~ 2 -- (3, 4, 5)
(1, 2, 3)& each *~ 2 -- (2, 4, 6)
-- monadic traversals (here each works like `traverse` for the list monad)
each (\x -> [x, x + 1]) (1, 2) -- [(1,2),(1,3),(2,2),(2,3)]
-- `each` is basically an overloaded "kitchen sink" traversal for
-- common containers. It also works on lists, vectors or maps, for example
[(3, 4), (5, 6)]& each . each +~ 1 -- [(4, 5), (6, 7)]
有沒有辦法重載一個函數'toList'爲二到五元組的元組? –
如果你做了很多 - 元組 - >列表,反之亦然 - 這很可能是你做錯了什麼或高度unidiomatic。 – epsilonhalbe
@Niklas:你可以使用一個typeclass來定義一個通用函數toList,然後爲每個元組arity重載創建實例。使用'-XMultiParamTypeClasses'和'-XFlexibleInstances'。 (a,b,c)= a:b:c:[]''實例ToList(a,b,c) ,a,a,a)a where toList(a,b,c,d)= a:b:c:d:[]'等 –