Combining Getters into a Fold

2019-08-14 07:54发布

In the spirit of the following questions:

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条回答
聊天终结者
2楼-- · 2019-08-14 08:32

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.)

查看更多
登录 后发表回答