Haskell:列表中每第二个元素加倍 [英] Haskell: Double every 2nd element in list

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

问题描述

我刚开始使用 Haskell,想写一个函数,给定一个列表,返回一个列表,其中每个第二个元素都加倍.

I just started using Haskell and wanted to write a function that, given a list, returns a list in which every 2nd element has been doubled.

到目前为止,我想出了这个:

So far I've come up with this:

double_2nd :: [Int] -> [Int]
double_2nd [] = []
double_2nd (x:xs) = x : (2 * head xs) : double_2nd (tail xs)

哪个有效,但我想知道你们将如何编写该函数.有没有更常见/更好的方法,或者这看起来是否正确?

Which works but I was wondering how you guys would write that function. Is there a more common/better way or does this look about right?

推荐答案

这还不错,以建议的修复为模.一旦您对基础库更加熟悉,您可能会避免显式递归而支持一些更高级别的函数,例如,您可以创建一个函数列表,其中每个函数都是 *2 并应用(zip) 将该函数列表添加到您的数字列表中:

That's not bad, modulo the fixes suggested. Once you get more familiar with the base library you'll likely avoid explicit recursion in favor of some higher level functions, for example, you could create a list of functions where every other one is *2 and apply (zip) that list of functions to your list of numbers:

double = zipWith ($) (cycle [id,(*2)])

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

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