Version 8, last updated by sebug at May 21, 2008 15:01 UTC

Scalit Tutorial

This tutorial will introduce you to the usage of the Scalit tool. Make sure you have correctly installed Scalit before.

Creating a literate program

A literate program contains both documentation and code interspersed in a fashion that helps the reader understand the program, but which is also compilable Scala code. For this, Scalit uses the same format that noweb does. A documentation chunk is started by writing an @ as a first character on a line. However, that is not necessary for the first documentation part because literate programs start with documentation until code is introduced.

Open your favorite text editor and write the following in the file fibonacci.nw:

\section{Fibonacci numbers with streams}

Adding some code

But now we will want to add some code to this document. Code is defined in chunks that will be puzzled together at the end. Chunks have the form <<chunk name>>. Let us add a first code chunk to the example file:

<<the fibonacci stream>>=
val S = Stream
def fib: Stream[Int] =
S.cons(0,
S.cons(1,
(fib zip fib.tail) map {
case (x, y) => x + y
}))

Note the code chunk definition imperatively has to be in the first column of a new line.

Adding a bit more documentation

After this code fragment, you can continue writing documentation. Write the following on a new line:

@ Note that through lazy evaluation we have no problem with
this infinite list.
The @ followed by a space character ensures that we are in documentation mode again.

Putting everything together

The document until now would just produce a pretty-printed version of the defined function. However, we want to compile an executable application. To tell Scalit how to put everything together, we use the special chunk <<*>>:

 

<<*>>=
object Fib extends Application {
<<the fibonacci stream>>

fib take 10 foreach { n => println(n) }
}

Note how we reference the code chunk that we defined before. When compiling, ScaLit will insert the content of this chunk at the position where it was referenced. With the addition of the last chunk, we have a compileable file now, so let us compile it.

Compiling it

To compile the file, execute the following command:

litcomp fibonacci.nw

This will generate the class Fib which (if everything worked as planned) you can now execute:

scala Fib

Creating the documentation

Ok, up until now, this was not quite as interesting as it could be. How about generating the documentation now? Execute the following:

sweave fibonacci.nw -o fibonacci.tex
perltex --latex=pdflatex fibonacci.tex

And voilà, you have a human-readable, pretty-printed version of your source code.

If you want to learn more about how to use Scalit, take a look at the command line usage