映射功能应用于列表的特定元素 [英] Map function applied to specific elements of the list

查看:60
本文介绍了映射功能应用于列表的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能:

mapAtOriginal :: (a -> a) -> [Int] -> [a] -> [a]
mapAtOriginal f is xs = helper 0 is xs
  where
    helper _ [] xs = xs
    helper c (i:is) (x:xs)
      | c < i     =   x : helper (c+1) (i:is) xs
      | otherwise = f x : helper (c+1)    is  xs

它是这样的:

mapAtOriginal (*2) [0,3] [1,2,3,4]   -- == [2,2,3,8]

所以我想重写它,但是要使用 map 函数.我了解 map 适用于列表中的每个元素,但是,我只需要将其应用于特定索引.

So I want to rewrite it but using a map function. I understand that map applies to every element of the list, however, I need it applied only for specific indices.

我该怎么办?

推荐答案

地图不知道它在列表中的位置".因此,您首先需要将该信息编码为元素本身.可以使用 zip [0 ..] 完成,它基本上用每个元素的出现位置对其进行注释.

map doesn't know "where in the list" it is. So you first need to encode that information into the elements themselves. This can be done with zip [0..], which basically annotates each element with position at which it occurs.

然后,在您的 map 函数中,您只需要在注释元组上进行模式匹配,并使用 if 决定是否应用其他元组元素的操纵器功能.

Then, in the function you map, you just need to pattern-match on the annotation-tuple, and use an if to decide whether or not to apply the manipulator function to the other tuple element.

请注意, zip map 的组合始终等同于单次通过

Note that the combination of zip and map is always equivalent to a single pass zipWith, so that's what you should preferrably use.

这篇关于映射功能应用于列表的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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