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

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

问题描述



到目前为止,我已经使用了Haskell,并且希望编写一个函数,给出一个列表,并返回一个列表,其中每个第二个元素已经加倍。已经拿出这个:

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

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

解决方案

这并不坏,以修复建议为模。一旦你更熟悉基础库,你可能会避免显式递归而转向一些更高级的函数,例如,你可以创建一个函数列表,其中每一个函数都是 * 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)])

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

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