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="http://horstmann.com/sjsu/cs152/schedule.html">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="http://szeiger.de/blog/2008/07/27/formal-language-processing-in-scala-part-1/">This
and href="http://debasishg.blogspot.com/2008/04/external-dsls-made-easy-with-scala.html">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="http://horstmann.com/sjsu/cs152/SL1.scala">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
while

Comments

Hi, you also might be interested implementing fac with utilizing the 'Stream' class when you want more the just a single value: http://gestalt.monoid.net/blog/2007/10/streams-for-incremental-and-tail....

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] http://www.scala-lang.org/node/111