inner methods and recursion

Steve Howell showell30 at yahoo.com
Tue Jan 19 03:55:58 CET 2010


On Jan 18, 6:07 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Mon, 18 Jan 2010 19:00:17 -0300, Steve Howell <showel... at yahoo.com>  
> escribió:
>
> > Hi, I have a style/design question relating to recursion and inner
> > methods.
>
> > I wrote some code recently that implements a recursive algorithm that
> > takes several parameters from the original caller.  Once the algorithm
> > starts running and recursing, those parameters remain the same, so I
> > define an inner method called "recurse" that essentially curries those
> > parameters.  In particular, the recurse method can get passed to a
> > callback method that the caller supplies, so that the caller can wrap
> > the recursive step with their own logic.
>
> Python already have lexical scoping, you can take advantage of it. On any  
> non-prehistoric version of Python you may write:
>
> def indent_lines(lines,
>              branch_method,
>              leaf_method,
>              pass_syntax,
>              flush_left_syntax,
>              flush_left_empty_line,
>              indentation_method,
>              get_block,
>              ):
>
>      def _indent_lines(lines):
>        output = []
>        while lines:
>          # ... the real work ...
>          # recursive call:
>          output += branch_method(prefix, block, _indent_lines)
>        return output
>
>      return _indent_lines(lines)
>
> The real work happens inside _indent_lines, and it has access to the outer  
> indent_lines scope, where all remaining parameters are defined.
>
> > The only thing I don't like about the technique that I'm using is that
> > it seems needlessly repetitive to define mostly the same parameter
> > list in two different places.  The repetition seems mostly harmless,
> > but it seems like some kind of a smell that I'm overlooking a simpler
> > way to write the code.  I just can't put my finger on what it is.
>
> Is the above technique what you were looking for?
>

That was exactly what I was looking for.  I just tried it out, and it
works perfectly. Thanks!




More information about the Python-list mailing list