Saturday 23 May 2015

Common Lisp Programming Tutorial with Examples

            In this post, we will see Lisp(Dialect: Common Lisp) programming which includes Comments, Simple Statements, Defining Variables, Constants, Operators, Output to screen, Input from user, Conditional Statements, Looping Statements, Arrays, List Processing, Multi-threading, Arithmetic Shift (ash), Logical AND (logand), Functions along with Example for area of circle. 
           
1. What is Lisp?
            Lisp stands for "List Processing". It was invented by John McCarthy. Lisp is second oldest High-Level programming language after Fortran. It is in existence from 1958 and it is mostly used for Artificial intelligence programming. It uses functional programming paradigm for programming; i.e. in Lisp, all statements are specified in terms of function calls. Statements are written in fully parenthesized prefix notation. For e.g. (+ 15 36), (f op1 op2), (+ (- 5 3) 4) etc. It has automatic garbage collection. Hence the programmer need not have to explicitly free the dynamically allocated memory. It has a strong support for recursion. That's why, it is widely used in Artificial Intelligence projects. It is also used for programming for Computer Games, Pattern Recognition, Real Time Embedded Systems.
           Lisp has many dialects; but most common dialects are Common Lisp and Scheme. In this post, I have considered Common Lisp dialect and used Steel Bank Common Lisp (SBCL) compiler for execution. (Download SBCL from this link http://www.sbcl.org/platform-table.html)



2. Three basic building blocks of Lisp programs

1. Atom (Number or String of continuous characters).
e.g. name, 2344, parag, jemmy245 etc.

2. List
         list is a sequence of atoms or other list enclosed in parenthesis.
e.g. (+ 5 3), (* 6 (+ 5 3)) etc.
3. String
        It is a group of characters in double quotation marks.
e.g. "I am  parag"
      "aaaabbbbb$$$$"

3. Getting sbcl prompt
           Type sbcl on terminal and press enter, you will get sbcl prompt. It is shown in following screenshot:


4. Putting Comment
        anything followed by ;

e.g. (write-line "Hello")   ;this is a comment



5. Simple Statements/Expressions

Examples:

(+ 3 2) gives 5
(- 4 6) gives -2
(* 3 17) gives 21
(/ 3 4) gives 3/4
(/ 55 5) gives 11
(+ (* 5 6) 9) gives 39
(/ 10 (- 5 3)) gives 5


6. Variables
            Variables are declared by using standard functions(similar to keywords in C/C++) as follows:

Example:
            Here, I have taken 'a' as variable and '3' as value assigned to a.
(defvar a 3)
(setf a 3)
(setq a 3)
              Data types of variables are decided based on the values assigned to the variables.

Examples: 
(setf a 4)
(setq b 7)
(+ a b) gives 11
(- a b) gives -3
(defvar c 7)
(+ a c) gives 11

Note: setf and setq gives warning(not error) that "variable is not declared" but still you can use it. defvar doesn't give any warning like setf as it defines the variable.

    
7. Constants
            To define a constant(similar to constant in C/C++), use defconstant.

Example: (defconstant p 4)


8. Operators
i. Arithmetic operators
       1) + for addition
       2) - for subtraction 
       3) * for multiplication 
       4) / for division 
       5) mod for finding modulus 
       6) incf increment operator 
               e.g. (defvar a 4)
                      (incf a) gives 5
                      (defvar b 6)
                      (incf b 2) gives 8
        7) decf decrement operator
               e.g. (defvar a 7)
                      (decf a) gives 6
                      (defvar b 9)
                      (decf b 4) gives 5

ii. Comparison operators
(= A B)
(/= A B)
(> A B)
(< A B)
(>= A B)
(<= A B)
(max A B)
(min A B)

iii. Logical operators
if A=NIL B=5
then
(and A B) returns NIL
(or A B) returns 5
(not A) returns T
(not B) returns NIL



 9. Showing Output on the screen (just like printf() in C Language)

1. To print a value of a variable (Use print or write function)
e.g.  (defvar a 7)
(print a) returns 7
(write a) returns 7


2. To print a line (Use write-line function)
e.g. (write-line "This is a Line") returns "This is a Line".


10. Taking input from the user (just like scanf() in C)
            Use standard function(read) to read a input from user and assign it to some variable.
e.g.:
(defvar a (read))

11. Decisions (Conditional Statements)
1.
(cond
(test1 action1)
(test2 action2)
.
.
.
(testn action n)
)

2. 
(if (condition) (action1) (action2))


3. (when (condition) (action1))

  
12. Loops (Looping Statements)
i. loop
e.g.
(defvar a 10)
(loop
(write a)
(write-line " ")
(setf a (+ a 1))
(when (> a 17) (return a))
)


ii. loop for
e.g.
(loop for a from 10 to 20
    do(print a)
)

iii. dotimes
e.g.
(dotimes (n 11)
(print (* n n))
)

iv. dolist
e.g.
(dolist (n '(1 2 3 4))
(print (* n n))
)



13. Array in Lisp

To create array with 10 cells
e.g. (setf array_example (make-array '(10)))

              Here array_example is the name of array and make-array is predefined function used to create an array of specified size (say 10).

To set content at particular index
(setf (aref array_example 6) 55)

              Here aref is predefined function, used to get the element at particular index.

To access content of 9th cell
(aref array_example 6)


14. List Operations

(car '(1 2 3 4 5)) returns 1
(cdr '(1 2 3 4 5)) returns (2 3 4 5) 
(car (cdr '(1 2 3 4 5))) returns 2
(car (cdr '(a (b c) d e))) returns (B C)
(cons 1 2)   returns (1.2)
(cons 'a 'b)   returns (A.B)
(cons 1 nil)  returns (1)
(car (cons 'a (cons 'b nil)))  returns A
(cdr (cons 'a (cons 'b nil))) returns (B)
(list 1 2 3) returns (1 2 3)

Note:
           We can combine multiple car and cdr into single word.
For e.g.
caar stands for car car
cadr stands for car cdr
caaar stands for car car car
cdddr stands for cdr cdr cdr
caddr stands for car cdr cdr

(write cadr '(4 3 2 1)) returns 3
(write cddr '(4 3 2 1)) returns (2 1)




15. Multi-threading in Lisp
            In Lisp, threads can be created by following syntax:
e.g. (sb-thread:make-thread(lambda() (write-line "Hello Parag")))

Note: make-thread() is a standard function from package sb.thread which is used to create one thread. If you want to create multiple threads, then call make-thread() multiple times. make-thread() accepts argument lambda() function. lambda() is anonymous function and it is just mentioned to specify contents of a thread.

 
16. Functions in Lisp
            In Lisp, functions can be defined by following syntax:

(defun function_name(arg1,arg2,........,argn)
(statement 1)
(statement 2)
.
.
.
(statement n)
)

e.g.
(defun add()
(print (+ 3 2))
)
           This function can be called as follows:
(add)
 
           Example of function with arguments:
(defun product(a b)
(print (* a b) )
)
          Calling above function:
(product 4 6)

17. Loading functions from a text file
              To load a function written in any text file, use following syntax:
(load "file_path/file_name.txt") 




18. Arithmetic Shift (ash)
              It is used to shift(bitwise) a decimal number.

Syntax: (ash number no-of-bits-to-be-shifted)

Example: 
(ash 4 1) gives 8
(ash 4 -1) gives 2
(ash 4 2) gives 16
(ash 13 1) gives 26
(ash 13 -1) gives 6


19. Logical AND Operation (logand)
                  It is used for binary AND operation between two numbers.


Syntax: (logand number1 number2)

Example: 
(logand 6 1) gives 0
(logand 3 1) gives 1
(logand 6 3) gives 2


20. Example: A function to find area of a circle

(defun areaofcircle()

(write-line "Enter radius")
(setf radius (read))(setf a (* 3.14 radius radius))
(write-line "Area of circle:")
(write a)
)
Note: Neglect warnings when you execute it from terminal.




Next: Six phases of Compiler with an Example  

Previous: OPENMP program for n-ary search algorithm    


3 comments:

  1. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    Regards,
    Python Training in Chennai|

    ReplyDelete
  2. You may have organized your folders and papers easily by putting them into file organizers that are bought in malls. But what about organizing your computer desktop? https://www.desktopcon.org/best-all-in-one-computer

    ReplyDelete