Instead of making that call from within
the function, we can have the function simply return the next function to be called.
An outermost loop can then call the function, receive as a return value the next
function to be called, call that, and so on. The call stack only ever has one element
in it, and we can happily have long chains or even cycles with no worries of
running out of space.
This is the approach taken in the Python example in Chapter 8. The main() function
there calls the current function, receives the next function back as the return value, and
calls that. Python is a suf?¬?ciently powerful language that functions are treated as ?¬?rst
class objects, which can happily be passed around and called.
GENERATOR OUTPUT PATTERNS 291
Other languages vary in their support for dynamic method invocation. Smalltalk,
Lisp, and Ruby predictably have no problems, but even the lowly BASIC-like OPL
used for end-user programming in Symbian is able to call functions whose name is
held in a string variable. While not quite as powerful as having functions as ?¬?rst class
objects, this is suf?¬?cient for our needs. C is happy to offer function pointers, but some
more recent languages have more trouble. The Standard Edition of Java can cope via
its invoke(), but this requires a fair bit more code than OPL or Smalltalk??™s perform:.
Pages:
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541