Skip to main content

Know When to Fold

Posted by cayhorstmann on October 5, 2008 at 8:26 PM PDT

I am teaching an undergraduate href="">course in programming
languages. We build interpreters and compilers for toy languages, in the
hope that students gain a basic understanding of syntax, semantics, and
language translation.

I use Scala to
implement the interpreters and compilers because of its nifty “combinator
parser” library. ( href="">This
and href="">this
blog have nice introductions into Scala combinator parsers.) Why not just lex
and yacc, the Model T of parser generators? My colleague is doing just that,
and it is a good thing because it gives students much-needed experience with C
programming. But I don't have the heart to see students suffer with pointer
errors. With Scala, we can implement an href="">interpreter for a simple
language that supports arithmetic, if/else, and closures, in < 150 lines
of code.

I am learning Scala on the job, and I don't know all of the language
features yet. In particular, surely there must be some kind of


Hi, you also might be interested implementing fac with utilizing the 'Stream' class when you want more the just a single value:

Hi, Folds are indeed very useful. Before anyone complains about weird symbols in Scala, one should note that there are non-symbolic alternatives for both variants represented here, they are unsurprisingly named foldLeft and foldRight. Regarding for/while loops, I am not sure if you were joking but Scala has while loops that behave like Java's and for/sequence comprehensions[1] that are more powerful than Java's for loop. [1]