140 likes | 351 Views
LISP. Symbolic Expressions (S Expressions) Syntax: Opening and Closing parenthesis having elements in between. List represented in LISP: (A B2 C3 Shahid) (A B (C D E) F G). Internal Representation. nil. B2. C3. Shahid. A. nil. F. G. A B. D. E. C. nil.
E N D
LISP • Symbolic Expressions (S Expressions) • Syntax: • Opening and Closing parenthesis having elements in between. • List represented in LISP: • (A B2 C3 Shahid) • (A B (C D E) F G)
Internal Representation nil B2 C3 Shahid A nil F G A B D E C nil
Functional Programming Defining Functions: Syntax: ( defun{Function Name} ( {parameters} {procedure or body of the function} ) ) Setting Values to variables: (setq A 2) or (set ‘A 2)
Arithmetic Operations (+ A B) means A+B (* 7 7) means 7*7=49 (- C D) means C-D (- (+10 20) 7) means ((10+20)- 7 = 23
Tree Diagram for Evaluation ( + (* 10 20) (* 2 3)) + (* 10 20) (* 2 3) * * 10 20 2 3
Built In Commands • Quote: returns the list as it is. • (quote(a b c)) or use ‘ instead of quote. • Returns (a b c) • List: load the argument as a list • (list(1 2 3 4)) • Returns (1 2 3 4) • Eval: evaluates the list or quoted list. • (eval ( quote (+ 2 3))) • Returns 5 • ( quote (+ 2 3)) • Returns (+2 3) • Nth n: returns the nth value of the list • (nth 0 (1 2 3 4 5 6)) returns 1 • (nth 3 (1 2 3 4 5 6)) returns 4 • (nth 5 (1 2 3 4 5 6)) returns 6
Examples (= (+ 5 1 ) 6 ) returns t ( > (* 5 6) (+ 4 5)) returns t Other List Operators (length ‘(1 2 3 4)) returns 4 (member 8 ‘(1 4 2 8 7)) returns t and if not present then returns nil (null ()) returns t
Assignments Statements • (setq a=0) returns 0 • (let ((a 3) b) ; local assignment (setq b 4) ;if you go outside let a goes to 0 (+ a b)) 7 • a 0 • b error b not bounded at the top level
Sample Programme Programme to add three numbers: ( defun ADDNUMBERS (num1 num2 num3) (setq sum 0); initialise the sum to zero (setq sum ( + sum num1); add first number (setq sum ( + sum num2)); (setq sum ( + sum num3)) );
Conditionals Command ‘cond’ Syntax: ( cond (<condition 1><action 1>) (<condition 2><action 2>) ------------------------ ------------------------ (<condition n><action n>) )
Example ( defun absolute_values(x) (cond ( ( < x 0) (-x)); (t x))) This programme returns the value of x as it is if x>0 otherwise returns -x
List Manipulation • Command ‘cons’ (cons ‘a ‘(b c)) returns (a b c) • Command ‘append’ does the same operation as cons • Command ‘car’ Returns the first element of the list • Command ‘cdr’ Returns the list excluding the first element
Examples • (cdr ‘((a b) (c d))) • returns ((c d)) • (car (cdr (car list1))) ca d ar (cadar x) • (car (car(x)) (caar x) • (car(car(car x))) (caaar x) • (cdr(car(cdr x))) (cdadr x)
Recursion • Write a programme that finds the factorial of a number Syntax: (defun factorial(x) ----------------- (recursive call)) ? recursive call: (* x ( factorial ( - x 1) ) )