One of the myths surrounding functional programming techniques is lazy evaluation does not pay.

Reading an old paper about dynamic creation of lexical analysers (lexers) I discovered an interesting use for lazy evaluation: Manuel M. T. Chakravarty writes a paper about lexer creation using combinators. He’s trying to obtain more flexibility by sidestepping the table-driven analysers used in static lexers and parsers.

He transforms the state table to a directed graph he builds lazily as the lexer reads the input. Using the laziness provided by the language he’s able to evaluate each part of the graph only once without keeping any overhead of what has already been evaluated.

This technique is a practical example of the usefulness of lazy evaluation, as he concludes:

non-strictness allows to significantly optimise the implementation of recursive combinators by exploiting cyclic structures. Furthermore, the lazy construction of the state transition graph minimises start-up costs when the input does not use all regular expressions of the lexical specification.

For the more bench mark oriented people, his results are pretty good. The handcoded lexer needs about 70% of the execution time of his dinamyc lexer.