且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Haskell:将列表中的每个第二个元素加倍

更新时间:2022-10-18 22:35:11

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

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


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?

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)])