Showing posts with label scheme. Show all posts
Showing posts with label scheme. Show all posts

2011-02-22

Experiments with Racket

In the last weeks I have played with Racket (formerly PLT Scheme), a powerful language derived from Scheme. Here I describe a couple of problems I solved using Racket, in order to underline the difference between this language and Python.

First, let me say that I am really impressed by the quality of the implementation of Racket. It is fast (apart from the execution times for the GUI), it has a huge set of libraries, it is easy to use and it has a number of nice facilities.

Project Euler again!

The first script I wrote was to solve one of the easiest problems proposed in the Project Euler site, that is problem 15. This kind of problem can be solved using a divide-and-conquer algorithm, so here comes my first attempt:

(define (num-of-solutions width height)
  (+ (if (> width 1)
         (num-of-solutions (sub1 width) height)
         1)
     (if (> height 1)
         (num-of-solutions width (sub1 height))
         1)))

Such solution relies on the fact that at any point in the grid one can only move left or down (provided that there is room to move in that direction), and that once you make a move you are trying to solve the same problem for a rectangular grid with a smaller size.

This solution however has a problem: when running num-of-solutions on a 20x20 grid, the function takes forever to evaluate. The problem lies in the fact that each non-trivial call to num-of-solutions spawns two recursive calls to itself, so that the number of calls grows quickly.

There is a simple solution: since many of the calls share the same parameters (and hence return the same number), we can use a technique called memoization: when calling num-of-solutions with some parameters for width and height, save the return value in a table so that subsequent calls to the function with the same parameter will simply look up the table instead of re-running the function. (See SICP for an example applied to the calculation of Fibonacci's numbers, a problem stunningly similar to the one we are solving here.)

In order to memoize num-of-solution I might have relied on standard techniques available for the Scheme language, but I instead had a look in the excellent Racket documentation and in PLaneT (the collection of separate packages available for Racket). In a few seconds I found the memoize package, which does exactly what I wanted: just changing define into define/memo will make num-of-solution orders of magnitude faster:

(require (planet dherman/memoize:3:1))

(define/memo (num-of-solutions width height)
  (+ (if (> width 1)
         (num-of-solutions (sub1 width) height)
         1)
     (if (> height 1)
         (num-of-solutions width (sub1 height))
         1)))

(num-of-solutions 20 20)

And here comes a nice touch. I did not know how to install this additional package in Racket, so I wrote the example above in the IDE and compiled it, hoping that any error message would help me to understand what to do. Guess what? The IDE automatically connected to PLanetT, downloaded and installed the package and continued the execution: in a few seconds I had the answer! (Compare this with Python: it is like if any time you import some library not available the interpreter downloads and installs it automatically. How nice!)

A more complex example

The second program I wrote was considerably longer. I had a problem with a TWiki site I am administering: every user would attach huge PDF files to wiki pages instead of properly using a separate site (I shall not bother you with details about how this site works: let just assume it is a FTP site). This caused any backup of the TWiki site to be quite huge, so I decided to fix this by manually moving the biggest PDF files to the FTP site and then change each link to the new place. As there are potentially thousands of links to fix, this clearly required an automated solution. And here comes Racket.

My plan was to download each page containing huge attachments in a text file, search for the TWiki markup signalling a link to any file already moved to the FTP site and modify the link properly. The caveats for such task are:

  1. I am not going to move all the files, just the biggest ones. So the program should be smart enough to decide which links to change and which not.
  2. So far I have considered the remote site as a FTP site, but this is not really the case. Specifically, to get a file from there the URL must contain the file name and a unique integer ID. So links to this site cannot be created automatically, they must be specified one by one. An example might be http:/foo/bar/filename.pdf?node=1234. Thankfully the file name is always present!

The program I created relies heavily on Racket's regular expressions, an addition of Racket over the Scheme language (note that regexps are native in Racket – like Ruby but unlike Python, which requires you to use import re at the beginning of your script). It takes two input files: the first one contains the wiki page, the second one contains a list of links to the remote site. The code extracts bare file names from the links and produces an associative list (similar to dictionaries in Python), which then uses to fix links in the wiki page.

The most difficult thing for me was to think how to implement iterations using recursion instead of for loops (and such code has a lot of iterations: looping over links, looping over markups…): however, I am willing to master this technique as the use of recursion is common in functional languages.

So far the code has worked like a charm. I have not benchmarked it, but it works so fast that execution times are negligible (of course I created a compiled executable in order not to start Racket every time I need to use it).

2010-12-20

The Scheme of things/2

In one of my previous posts I compared Clojure with Python by implementing two identical versions of a program to solve problem 34 from Project Euler in both languages. My results showed that Clojure was able to be three times faster than Python when type hinting (TH) was enabled (even without TH Clojure was however faster than Python). My idea was then that any type-hinted (semi-)interpreted language like Clojure would have reached the same speed.

In the last month I have run some other tests, and I must say that my idea has changed. A number of Scheme/Common LISP implementation have proven to be even faster than Clojure, and this without type hints!

I am not going to provide my Common LISP and Scheme programs, as they are trivial conversions of the Clojure program I presented before. These are the compilers/interpreters I used to write and run my test programs:

NameVersionLanguageTiming
Ikarus0.4 RC1Scheme14
Larceny0.97Scheme15
Bigloo3.5aScheme16
Steel Bank CL1.0.44Common LISP17
MZScheme (DrRacket)5.0.1Scheme17
STklos1.0Scheme43
CMU CL20bCommon LISP47
Clozure CL1.5Common LISP62
Chicken4.6.3Scheme93
Chicken4.4.0Scheme102
CLISP2.49Common LISP106
CPython (fast)2.6.6Python135
CPython2.6.6Python145
ECL10.4.1Common LISP169

The "CPython (fast)" entry is a rewrite of my original Python program so that the body of solution does not call other Python functions:

sum ([num for num in xrange (10, max_n)
      if num == sum ([FAST_FACT[digit]
                      for digit in [int(x)
                                    for x in list (str (num))]])])

A few notes about these results:

  • There is more than one order of magnitude between the slowest implementation (ECL) and the fastest (Ikarus Scheme);
  • Compilers without TH (e.g. Ikarus, Larceny, Bigloo, SBCL) run much faster than Clojure with TH. I was really surprised!
  • Avoiding function calls make CPython faster, but not much faster;
  • The fastest program runs using Ikarus, a compiler in alpha stage that has been put on hiatus after the author (apparently) changed his job. What a pity! (Note however that Marco Maggi has forked Ikarus into Vicare, which seems to be actively developed.)
  • While I had to change my Scheme program in order to make it runnable under various Scheme compilers/interpreters (nothing sensational, just one or two lines at the beginning), my Common LISP program ran unchanged under SBCL, ECL and CCL. One point for portability to Common LISP!

Here is a barchart of the results (click to zoom):

Update: After a suggestion by Water I included in my benchmarks also CLISP (and corrected the name) and CMU Lisp (which was mentioned in one of the pages at CLISP's site as being faster than CLISP – and indeed it is). In both cases I first compiled the program and then timed the execution of the bytecode. I have also added MZScheme, which I left out in the first version of this post. The table and the chart have been updated accordingly.

2010-11-18

The Scheme of Things/1

In one of my previous posts I anticipated that I was going to study some functional programming languages in order to better understand how to write parallel programs for multi-core and multi-CPU architectures. During my (very slow!) quest I re-discovered a old language I used to be quite fond of: Scheme, a LISP-like language which dates back to the 1970s. In this post and the following I shall provide some information about my relationship with this wonderful small language, as well as some insights about how it might be useful for scientific computations.

Music Typesetting and Scheme

My first experience with Scheme dates back to about ten years ago. I am a passionate music lover, and I was looking for a good program to typeset music. I found the marvellous GNU Lilypond, which was well-suited for what I wanted to do at the time. I contributed a lot of pieces to the Mutopia project (mostly scores by Mozart and other classical composers, see e.g. Mozart's String Quartets from Op. 10), and at the same time I became quite good in extending Lilypond using its scripting language. Guess which language it was? Of course Scheme! Lilypond used GNU Guile, a Scheme interpreter sponsored by the Free Software Foundation (yes, the guys behind Gnu Emacs and GCC). The intention of the Guile coders was to develop an interpreter that could be used by other projects to provide a "plugin" language usable for extending large applications. (Unfortunately, the project did not suceed in gaining enough popularity and it has developed at a quite slow pace: just have a look at these dates and version numbers.)

Partial Differential Equations and Scheme

During 2001-2002 I worked on my master thesis. The main objective of the work was to study the solution of the heat equation given some well-defined boundary conditions, in order to better understand some properties of the reference loads of the Planck/LFI instrument. One of the tools I developed for my study was a small C program which used the Crank-Nicholson implicit method to solve the one-dimensional heat equation numerically.

Since the objective of the program was to simulate how the temperature of a body changes with time, the output was a quite large set of numbers: for each time step, there were tens of temperatures (sampled on a regular grid) that the program printed. According to the type of analysis I was doing, I had to throw away irrelevent temperatures and keep the ones I was interested: at the beginning I was using GNU Awk for the job, but this was not the optimal solution. At some time I realized that what I needed was some way to attach "plugins" to my program: each plugin would have been a small program which would have driven the program and instructed it to print only the information needed by the ongoing analysis.

This of course called for an embedded interpreter. At the time the one I knew best was of course Guile (see above), so I decided to implement Guile bindings in my program. All worked like a charm: once the C program was properly debugged and produce reasonable results, I could start writing Scheme snippets to perform every analysis I wanted and attach them to the program without the need to recompile it. It was like a dream! (Actually, one of the appendices of my thesis contains the source code for some of those Scheme plugins.)

Thermal Modeling and Scheme

After having defended my thesis, I continued studying the thermal performances of Planck. We used a number of closed-source thermal modeling tools based on Fortran 77 for doing the most complex analysis. Such tools required the user to create huge text files (called model files) containing details about how the object under study was to be discretized and what were its characteristics (e.g. density, specific heat…) at each point. Such files were interwoven with Fortran 77 code which calculated and extracted the information required for the analysis (much like Scheme plugins did for my program).

Managing such files was a pain, so I created a couple of programs to help me in the task. The first program, Thermal Scheme, looked for a specific signature in the contents of model files: every text between #{ and #} was interpreted as Scheme code, which was run and its result replaced the Scheme code in the model file. Therefore, giving a text file like

Hello #{(display "world")#}!

Thermal Scheme would translate it into

Hello world!

Of course, Thermal Scheme provided a number of Scheme functions to easily define and discretize complex structures.

Thermal Scheme was able to act like a "data provider": when some command-line flag was used, the program recorded every Scheme definition and built a text file containing a 3-D representation of the object. A companion program, Thermal Viewer, was able to connect to "Thermal Scheme", get this text file and create an interactive 3-D view of the object using OpenGL.

Things Go Awry!

After a few months working with Thermal Scheme, I was supposed to move to the Rutherford Appleton Laboratory (Oxford, UK) to continue working on Planck thermal analyses. I even arranged a demo of the capabilities of Thermal Scheme! But then in Spring 2003 the Italian Government obliged me to do ten months of civilian service, so I was forced to decline that job offer. Ten months after (May 2004) my duties were over and I got a temporary position at the National Institute of Astrophysics, where my first duty was to build a medium-sized software tool for Planck/LFI using RSI IDL (a Fortran-like language for data analysis). So I started studying IDL and completely forgot about Scheme… till a few weeks ago!

In one of my next posts I shall tell you how Scheme evolved in the meantimes, and what I discovered about the performances of some of the currently developed Scheme interpreters/compilers. Stay tuned!