将吸气剂合并为一个折叠 [英] Combining Getters into a Fold
问题描述
本着以下问题的精神:
我现在正在寻找一种将多个 Getters 合并成一个折叠,如下所示:
('a','b','c','d')^ ..(_1≠_2 <> _3)
会导致这种情况:
['a','b','c']
但上面的代码实际上失败并显示以下消息:
<$ p
(Accessor(Endo [Char])(Char,Char,Char,Char)))
没有实例,因为使用<> ;'
那我该如何实现呢?这是可能的吗?
import Data.Monoid
import Control.Lens
实例Monoid r => Monoid(Accessor r a)其中
mempty =访问者mempty
mappend(访问者a)(访问者b)=访问者$ a<> b
测试:
* Control.Lens Data.Monoid> ('a','b','c','d')^ ...(_1≠2‖3)
abc
(更新:现代版透镜
版本默认包含此实例,所以第二个代码片段应该只用于箱子。)
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?
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.)
这篇关于将吸气剂合并为一个折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!