将函数应用于列表中的每个第二个元素 [英] Apply a function to every second element in a list

查看:54
本文介绍了将函数应用于列表中的每个第二个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对列表中的每个第二个元素应用一个函数:

I'd like to apply a function to every second element in a list:

> mapToEverySecond (*2) [1..10]
[1,4,3,8,5,12,7,16,9,20] 

我编写了以下函数:

mapToEverySecond :: (a -> a) -> [a] -> [a]
mapToEverySecond f l = map (\(i,x) -> if odd i then f x else x) $ zip [0..] l

这行得通,但是我想知道是否还有一种更惯用的方式来做类似的事情.

This works, but I wonder if there is a more idiomatic way to do things like that.

推荐答案

我还没有写很多Haskell,但这是我想到的第一件事:

I haven't written very much Haskell, but here's the first thing that came into mind:

func :: (a -> a) -> [a] -> [a]
func f [] = []
func f [x] = [x]
func f (x:s:xs) = x:(f s):(func f xs)

这有点麻烦,因为您不仅要处理空列表,而且还要处理包含一个元素的列表.伸缩性也不太好(如果您需要三分之一,或者

It is a little ulgy, since you have to not only take care of the empty list, but also the list with one element. This doesn't really scale well either (what if you want every third, or

@Landei指出,然后写

One could do as @Landei points out, and write

func :: (a -> a) -> [a] -> [a]
func f (x:s:xs) = x:(f s):(func f xs)
func f xs = xs

为了消除对 [] [x] 的丑陋检查,恕我直言,这使它的读取变得更难一点(至少第一次).

In order to get rid of the ugly checks for both [] and [x], though, IMHO, this makes it a little harder to read (at least the first time).

这篇关于将函数应用于列表中的每个第二个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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