Blog - Higher Order Perl - recursion vs. iterators

Added on Tuesday, 2010-06-15 13:48 CEST in category Programming
Lately I've been reading a lot of Higher Order Perl, which introduces a lot of really nice Perl programming techniques. So far my favorite technique is the use of iterators instead of recursion.

A program that may possibly recurse a lot, e.g. if calculating permutations, may well run out of memory before it's done calculating everything. It may also take a lot of time to recurse through the entire system's file structure. The program keeps waiting and waiting for results, and suddenly it gets all of them at once.

An iterator solves this problem by eliminating actual recursion by instead keeping track of how the program would recurse. On each call the iterator calculates where to go next, and calculates and returns just one value at a time. This saves a lot of memory and only returns values when they're needed. Also, the program won't have to wait for all the processing to be finished. It can start processing the first value straightaway.

Check out chapter 4.3.1 and chapter 5 of Higher Order Perl for more details.