将吸气剂合并为一个折叠 [英] Combining Getters into a Fold

查看:90
本文介绍了将吸气剂合并为一个折叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本着以下问题的精神:



我现在正在寻找一种将多个 Getters 合并成一个折叠,如下所示:

 ('a','b','c','d')^ ..(_1≠_2 <> _3)

会导致这种情况:

  ['a','b','c'] 

但上面的代码实际上失败并显示以下消息:

<$ p
(Accessor(Endo [Char])(Char,Char,Char,Char)))
没有实例,因为使用<> ;'

那我该如何实现呢?这是可能的吗?

解决方案

这也可以用这个答案发布的Monoid实例:

  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



abc只是['a','b','c'],所以这就是你想要的。



(更新:现代版透镜版本默认包含此实例,所以第二个代码片段应该只用于箱子。)


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆