Chapter 2. Creating Your First Lisp Program

Now that we’ve discussed some of the philosophy of Lisp and have a running CLISP environment, we’re ready to write some actual Lisp code in the form of a simple game.

The Guess-My-Number Game

This first game we’ll write is pretty much the simplest game imaginable. It’s the classic guess-my-number game.

In this game, you pick a number from 1 to 100, and the computer has to guess it.

The following shows what game play might look like if you pick the number 23. The computer starts by guessing 50, and with each successive guess, you enter (smaller) or (bigger) until the computer guesses your number.

> (guess-my-number)
50
> (smaller)
25
> (smaller)
12
> (bigger)
18
> (bigger)
21
> (bigger)
23

To create this game, we need to write three functions: guess-my-number, smaller, and bigger. The player simply calls these functions from the REPL. As you saw in the previous chapter, when you start CLISP (or any other Lisp), you are presented with the REPL, from which the commands you type will be read, then evaluated, and finally printed. In this case, we’re running the commands guess-my-number, smaller, and bigger.

To call a function in Lisp, you put parentheses around it, along with any parameters you wish to give the function. Since these particular functions don’t require any parameters, we simply surround their names in parentheses when we enter them.

Let’s think about the strategy behind this simple game. After a little thought, we come up with the following steps:

  1. Determine the upper and lower (big and small) limit of the player’s number. Since the range is between 1 and 100, the smallest possible number would be 1 and the biggest would be 100.

  2. Guess a number in between these two numbers.

  3. If the player says the number is smaller, lower the big limit.

  4. If the player says the number is bigger, raise the small limit.

image with no caption

By following these simple steps, cutting the range of possible numbers in half with every guess, the computer can quickly hone in on the player’s number.

This type of search is called a binary search. As you may know, binary searches like this are used all the time in computer programming. You could follow these same steps, for instance, to efficiently find a specific number given a sorted table of values. In that case, you would simply track the smallest and largest row in that table, and then quickly hone in on the correct row in an analogous manner.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.240.252