递归函数内的枚举数 [英] Numeration count inside a recursive function

查看:107
本文介绍了递归函数内的枚举数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似的事情:

 >枚举[banana,potato,ice] 
[(1,banana),(2,potato),(3,ice)]

我写道:

  enumerate :: [String]  - > [(Int,String)] 
enumerate [] = []

/管理int计数器?有没有办法做到这一点没有支持功能?



更新:我知道 Zip 函数。但为了学习的目的,我想实现我自己的zip功能。



更新2:目前代码



这是我迄今为止所做的,使用支持功能。考虑到:



1)我想实现我自己的 zip 函数;

2 )我不想改变函数struct:

  enumerate :: [String]  - > [(Int,String)] 

enumerate :: [String] - > [(Int,String)]
枚举[] = []
枚举列表= aux 1列表


aux :: Int-> [String] - > [(Int,String)]
aux _ [] = []
aux i (x:xs)= [(i,x)] ++ aux(i + 1)xs

有没有可能改进这个功能?由于我不想再添加最后一个函数,所以我认为支持函数是唯一的出路,对吗?

解决方案

>不要害怕写一个支持函数,其实看到它是一个机会:为什么任意的起始值1?为什么没有函数?

 > enumerateFrom 42 [banana,potato,ice] 
[(42,banana),(43,potato),(44,ice)]

一旦你有了, enumerate 很容易。

编辑
或者给你的 aux 函数一个真实的名字,恕我直言 enumerateFrom 很好,或者将它移动到一个 where 子句,如果你已经知道了。然后听chi,使用 x:... 而不是 [x] ++ ...


I want do do something like:

>enumerate ["banana", "potato", "ice"]
[(1, "banana"), (2, "potato"), (3, "ice")]

I wrote:

enumerate :: [String] -> [(Int, String)]
enumerate [] = []

How may I control/manage the int counter ? Is there a way to do that without a support function ?

Update: I know about Zip function. But for matter of study, I want to implement my own zip function.

Update 2: Currently Code

This is what I did so far, using a support function. Considering that:

1) I want to implement my own zip function;
2) I do not want to change the function struct:

   enumerate :: [String] -> [(Int, String)]  

enumerate :: [String]->[(Int,String)]
enumerate [] = []
enumerate list = aux 1 list


aux :: Int->[String]->[(Int, String)]
aux _ [] = []
aux i (x:xs) = [(i, x)] ++ aux (i+1) xs

Is it possible to improve this function ? As I don't want to add one more last to the function, so I think support function is the only way to go, right ?

解决方案

Don't be afraid to write a support function, in fact, see it as opportunity: Why the arbitrary starting value 1? Why not have a function

>enumerateFrom 42 ["banana", "potato", "ice"]
[(42, "banana"), (43, "potato"), (44, "ice")]

Once you have that, enumerate is easy.

Edit: Either give your aux function a real name, IMHO enumerateFrom is good or move it into a where clause if you know that already. And listen to chi, use x : ... instead of [x] ++ ...

这篇关于递归函数内的枚举数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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