递归函数内的枚举数 [英] Numeration count inside a recursive function
问题描述
我想做类似的事情:
>枚举[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)]
一旦你有了, 编辑: I want do do something like: I wrote: 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 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 Once you have that, Edit:
Either give your 这篇关于递归函数内的枚举数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
或者给你的 aux
函数一个真实的名字,恕我直言 enumerateFrom
很好,或者将它移动到一个 where
子句,如果你已经知道了。然后听chi,使用 x:...
而不是 [x] ++ ...
>enumerate ["banana", "potato", "ice"]
[(1, "banana"), (2, "potato"), (3, "ice")]
enumerate :: [String] -> [(Int, String)]
enumerate [] = []
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
>enumerateFrom 42 ["banana", "potato", "ice"]
[(42, "banana"), (43, "potato"), (44, "ice")]
enumerate
is easy.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] ++ ...