开发者

Indexing Recursion without using an index parameter

开发者 https://www.devze.com 2023-04-12 22:48 出处:网络
Am trying to write a recurssive function to do something, but at each step I\'d like to know the 开发者_开发技巧current depth / index in the tree. So how can I achieve this without use of an index par

Am trying to write a recurssive function to do something, but at each step I'd like to know the 开发者_开发技巧current depth / index in the tree. So how can I achieve this without use of an index parameter in the function signature?

Something like:

rec_fn n = do print index
              do_something n
              if n > 0
                then rec_fn (n-1)
                else print "end"

so how do I obtain index, without doing something like:

rec_fn n i = do print i
                do_something n
                if n > 0
                  then rec_fn (n-1) (i+1)
                  else print "end"


Well, if your function depends on the current index it should get it as an argument. Otherwise you break many nice features of pure functions, such as referential transparency.

If its about getting rid of the extra parameter at the function call, you can use a helper function like the following:

rec_fn n = go n 0
    where go n i = do print i
                      do_something n
                      if n > 0
                         then go (n-1) (n+1)
                         else print "end"

This is a pattern that's used quite often in Haskell.


It really depends on what exactly is wrong with the index argument. Do you want to get rid of it, because you don't want to pass it around all the time? Then the answer is: You shouldn't do that, because it would make your code more difficult to understand. However, if you insist, you can use a state monad. Again: If your reason is convenience, really don't do it. In almost all cases and particularly in your case it will be less convenient in the end.

A legitimate reason for getting rid of an argument is when it's redundant like in a list length function, which always initializes its accumulator with 0. In that case see bzn's answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号