Stepping into Lisp programming

Actually I’m not going to provide a series of Lisp tutorials here. If you want to learn Lisp and it’s syntax I would like to recommend you to follow these guides Lisp tutorial, Common Lisp – Introduction, Tutorials and Resources. Go there and study it first.

If you still don’t know why Lisp is called an awesome language see the previous post.

The best way to learn programming is just doing it. Learn to do it by doing it! If you are an amateur to the Lisp programming (even though me too) you can try out the below working program yourself now.

Download GNU CLISP 2.49. Setup it, launch it. Startup screen is as below.

clisp-startup-screen

Lisp is works as an interpreter. You can type lisp commands on the console directly and run them. Either you can make an external Lisp file by using a simple text editor and run it on the Clisp console.

Create the following Lisp file in notepad. This is my first Lisp program created: A prime number finder, which I wrote as my very first Lisp program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(defparameter isprime 1)
 
(defun prime-numbers (from to)
(if (> from to) nil
(progn
(devider from from)
(if (= isprime 1) (print from))
(setf isprime 1)
(prime-numbers (+ from 1) to))))  
 
(defun devider(num val)
(if (< num 3) nil 
(progn
(if (= (mod val (- num 1)) 0) (setf isprime 0))
(devider (- num 1) val)))
)
(defparameter isprime 1)

(defun prime-numbers (from to)
(if (> from to) nil
(progn
(devider from from)
(if (= isprime 1) (print from))
(setf isprime 1)
(prime-numbers (+ from 1) to))))  

(defun devider(num val)
(if (< num 3) nil 
(progn
(if (= (mod val (- num 1)) 0) (setf isprime 0))
(devider (- num 1) val)))
)

The above lisp program consist of two functions (prime-numbers, devider) and one global variable (isprime). Actually the “devider” functions is called by the “prime-numbers” function internally. So the main function that we use to run the program is “prime-numbers”. It has two parameters called “from” and “to” which use to pass start-point and ending-point of the numbers range when we call it.

Copy the above code into an text editor and save the file as “prime-num-finder.lisp”. Remember to save it with the “.lisp” extension.

saving-lisp-file

Turn back to the Clisp console. Use the following command to load the lisp file you created. Remember to add an additional “\” for each back slash on the file path.

(load “C:\\prime-number-finder.lisp”)

loading-lisp-file

The “load” command exactly works as if you had typed in the code directly at the command line. After loading the file successfully, the “prime-number” function on the lisp file can be called as (prime-numbers [start point] [ending point]). Let’s try out to find the prime numbers between 1 and 10.

(prime-numbers 1 10)

calling-method

The numbers given to the function parameters are 1 and 1o. So the output prime numbers displaying as 1, 2, 3, 5, 7.

Leave a Reply