Scheme

My Introduction to Scheme

The other night, I was reading through Hacker News or Programming Reddit or something and I found an article about writing compilers that supposedly simplified it enough that it could be taught to beginner-level computer science students. It uses potentially hundreds of complier passes to make simple transforms to the code until it has completed its task.

I thought that I’d check it out and I saw that it was written in Scheme. I personally hadn’t spent any time in LISP or any LISP dialects, so it seemed like something interesting to dive in to.

On my Mac, using Homebrew, it was a breeze to get started. At first, I just typed

brew search scheme

I found what I was looking for and then typed

brew install scheme48

Here is an example of what you would see installing it on a Mac.
Install Scheme via Homebrew on Mac OSX

That’s it! (if you are on Windows, you can get install instructions here)

The only things I knew about Scheme were that it was functional and there were a lot of parentheses. I was right on both accounts. Aside from a few exercises where you were to type a number and have it spit back out to you, the first thing you run into is this:

(* 2 2)

Well, at first glance, stuff like that will throw you a little bit. However, with only a little bit of thought, you can see that it makes perfect sense. We have to think functionally. The parentheses tell us that this group is all one function call and reading left to right we see that we are calling the multiplication function – the * – and passing in the numbers 2 and 2 as arguments. That’s it. So (* 2 2) outputs 4 and (* 2 3 4) outputs 24. Also, we need the parentheses. Without them, you don’t get the desired result as you can see below.

Multiplication in Scheme

What about control flow? That, too, is very simple. The syntax is simply (if (condition) result1 result2). It is very similar to an IIF statement, but without the commas. If you take this code, you get the result pictured below.

(if (< 4 5) "four is less than 5" "four is not less than five")

Simple If Statement in Scheme

If you are having any trouble making sense of it, it might be helpful to think of this code in terms of how it breaks out in C#

if (4 < 5)
{
     return "four is less than five";
}
else
{
     return "four is not less than five";
}

I hope that if the Scheme code was confusing to you, that the C# translation helped a bit. You'll notice that just as a Ruby function returns the last thing that was evaluated, so too does Scheme. That's why there are no return statements in my Scheme example, but there are in the C# example.

Next time, we'll look at more complex if statements and travel down the functional road a little further.

Leave a Reply

Your email address will not be published. Required fields are marked *