Combining Getters into a Fold

半城伤御伤魂 提交于 2019-12-11 09:20:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!