Sunday, December 27, 2009

Trying out the examples from 'The Little Schemer' book

This delightful book leads you through the basic elements of programming in Scheme (a Lisp dialect) via a series of dialogues with well-chosen questions and exercises.

To try out the examples from The Little Schemer, you must first download1 PLT-Scheme. This will install DrScheme, which is the IDE you will use to type in the Scheme examples.

As a language, I chose Module in DrScheme and it seems to be suitable for trying out the examples.

Once the language is set, you need to start each file with the following line:

#lang scheme

The upper section of the screen is used to enter all the definitions and the lower part of the screen is used to execute those functions you defined in the upper part.

Minor Changes

Something you need to be careful about are the minor syntax changes. This is because there are slight changes from the examples in the book to the real Scheme.

One of changes is the way you call identifiers. Identifiers require an apostrophe (') in Scheme, but in the book the apostrophe is not used in the examples.

This is mentioned in page 3 of the book:

L, S: (quote atom) or 'atom

This means that, for example, to test the atom? function (or any function), you need to call it like such:
(atom? 'elem1)

Same goes for when the identifier is a list:

(atom? '(peanut butter jelly time))

The Apostrophe

The apostrophe is a shorthand notation of the (quote ...). Basically, you are saying the interpreter to not evaluate the name but only replace it with its value, verbatim.
Therefore, the following two lat? questions are the same thing:

(lat? (quote (peanut butter jelly)))


(lat? '(peanut butter jelly))

If you do not put the apostrophe, you are signaling the interpreter to use the variable. This can be clearly illustrated with the following example:

(let ((x 42))
  (display x) (newline)
  (display 'x) (newline))

The output of the above code is:

1 If you don't want to download PLT-Scheme, you can use an online interpreter. Two of which you can try are SISC and CodePad