问题
In the spirit of the following questions:
- Getting multiple results from map with “lens”
- Combining lenses
I am now looking for a way to combine multiple Getters into a single Fold, so that something like the following:
('a','b','c','d') ^.. (_1 <> _2 <> _3)
would result in this:
['a', 'b', 'c']
But the code above actually fails with the following message:
No instance for (Monoid
(Accessor (Endo [Char]) (Char, Char, Char, Char)))
arising from a use of `<>'
So how do I achieve this? Is this possible at all?
回答1:
This is also possible with the Monoid instance posted in this answer: Getting multiple results from map with lens
import Data.Monoid
import Control.Lens
instance Monoid r => Monoid (Accessor r a) where
mempty = Accessor mempty
mappend (Accessor a) (Accessor b) = Accessor $ a <> b
Test:
*Control.Lens Data.Monoid> ('a','b','c','d') ^.. (_1 <> _2 <> _3)
"abc"
"abc" is just ['a','b','c'], so this does what you want.
(Update: Modern lens
versions include this instance by default, so the second code snippet should just work out of the box.)
来源:https://stackoverflow.com/questions/17552835/combining-getters-into-a-fold