Haskell:将列表中的所有索引更改为某个值 [英] Haskell: change all indices from a list to some value

查看:167
本文介绍了Haskell:将列表中的所有索引更改为某个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我为这个列表中的一些索引提供了一个对象列表和另一个列表,那么是否有一种简单的方法可以用索引列表中的索引更改为不同值的列表中的每个对象?

If I am given a list of objects and another list for some indices from this list, is there an easy way to change every object in this list with an index from the list of indices to a different value?

例如我希望存在一些函数f,使得

E.g. I am hoping there exists some function f such that

f 0 [4,2,5] [6,5,8,4,3,6,2,7]

会输出

[6,5,0,4,0,0,2,7]


推荐答案

这是一个美丽的版本,它使用 lens

Here is a beautiful version that uses lens:

import Control.Lens

f :: a -> [Int] -> [a] -> [a]
f x is = elements (`elem` is) .~ x

base 之外没有任何依赖关系的高效版本。基本上,我们从排序(并从索引列表中删除重复项)开始。这样,我们不需要扫描整个列表中的每一个替换。

Here is an efficient version that doesn't have any dependencies other than base. Basically, we start by sorting (and removing duplicates from the) indices list. That way, we don't need to scan the whole list for every replacement.

import Data.List

f :: a -> [Int] -> [a] -> [a]
f x is xs = snd $ mapAccumR go is' (zip xs [1..])
   where
     is' = map head . group . sort $ is
     go [] (y,_) = ([],y)
     go (i:is) (y,j) = if i == j then (is,x) else (i:is,y)

这篇关于Haskell:将列表中的所有索引更改为某个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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