Transcript LISP
Artificial Intelligence LISP Seong-shin Kim Computer Science and Engineering Dept. LISP 개요 MIT의 John McCarthy교수에 의해 1958년 개발 종류가 많음: Scheme, Interlisp, MacLisp Standard: CommonLisp(1981년) 모든 AI Lab에서 사용 LISP is symbolic programming(기호처리 언어) LISt Processing Language -예 (x y z), (x (a b) z) Procedural Language Interpreter Language with Compiler Support 2 LISP Object(구성 요소) SQRT LONG_NAME_OK -17.5 NIL T ATOM(원소) (John Mary SoonHee) (PLUS 2 3) (TIMES (PLUS 2 3) 6) LIST(리스트) S- Expression 3 LISP 실행 과정 Basic User Interface Read an Expression Evaluate the Expression Print the Evaluate result 4 LISP의 사용자 정의 함수 (f arg1 arg2.. ) f : 함수 이름 arg1,arg2,.. : argument list Arguments are evaluated first then f is applied on them (foo (bar y1 y2) x2 x3) (+ 3 (* 5 9)) 5 LISP의 사용자 정의 함수 (f arg1 arg2.. ) f : 함수 이름 arg1,arg2,.. : argument list Arguments are evaluated first then f is applied on them (foo (bar y1 y2) x2 x3) (+ 3 (* 5 9)) 6 List Structure Cons cell의 구조 첫번째 요소 dotted pair (A . B) List (A B) A A B 나머지 리스트 B ( + (+ x y 3))리스트의 표현 + 3 + x y 7 LISP의 내장 함수 Quote (quote X) => ‘X evaluates to X,X를 return함 ’(a b c) => (a b c) (plus 1 2 3) (times 2 3 4) (difference 5 4) (sqrt 64) 8 LISP의 내장 함수 car, cdr : 리스트 조작에 사용되는 중요한 두 가지 함수 car : 콘셀의 왼쪽 방에 있는 값, 리스트의 첫번째 구성 요소 cdr : 콘셀의 오른쪽 포인터가 가리키는 리스트, 첫 구성요소를 뺀 나머지 a cdr car b c ’(a b c) => (a b c) (car ’(a b c)) => a (cdr ’(a b c)) => (b c) (car ’((a b) (c d)) => (a b) (car (car ’((a b) (c d)) ) => a (caar ’((a b) (c d)) ) => a : car을 적용한 결과에 car을 적용한 결과 9 LISP의 내장 함수 • (cdar ’((a b) (c d))) => (b) : car를 적용한 결과에 cdr을 적용함을 의미 • (cadar ’((a b) (c d))) => b :car->cdr->car • car와 cdr의 a와 d를 3개까지 결합하여 사용 가능 • append 함수 • (append ’(a b c) ’(d e)) => (a b c d e) 10 LISP의 내장 함수 • 리스트를 만드는 함수 cons함수와 list함수 • (cons ’a ’b) => (a . b) • (cons ’a (cons ’b nil)) => (a b) • (list ’a ’b ’c) => (a b c) • 위 list함수는 아래와 같은 cons함수와 동일 (list ’a ’b ’c) => (cons ’a (cons ’b (cons ’c nil)) ) • append 함수 • (append ’(a b c) ’(d e)) => (a b c d e) 11 논리와 진리값 (= 1 1) => t (> 1 2) => nil (false의 의미) (atom ’a) => t (atom ’(a b c)) => nil (listp ’(a b c)) => t (eq ’a ’a) => t (eq ’(a b c) ’(a b c)) =>nil (equal ’(a b c) ’(a b c)) => t ; 요소들의 구조적 형태와 내용 의 동일성을 묻고 eq는 요소들의 포인터의 동일성을 묻는다 [그림 16-4 참조] 12 DEFUN(1) (defun function-name(arg-list) function-body ) (defun square(x) (* x (square 3) x)) => 9 => (defun my-square(x) (if evenp(x)(* x x)(+ x x))) (my-square 3) 6 (my-square 4) => 16 13 DEFUN(2) (defun foo (first &optional (second 20)) (+ first second)) (foo 3) => 23 (foo 3 4) = 7 (foo 3 4 5) => 7 14 실습 문제 다음 S형의 평가결과는 어떠한가? (eval ’( a b c)) (eval ’(+(* 3 5)(-5 2) 4 3)) (eval (+(* 3 5)(-5 2) 4 3)) 다음 LISP를 실행했을 때 결과는? (cons ’a ’b ’c) (cons ’a (cons ’b( cons (cons ’c nil) nil ))) (cons ’a (cons (cons ’b nil)(cons ’c ( cons ’d nil) ))) 다음을 평가하라. (car (cdr ’(a b c d))) (cdr (car (cdr ’(a (b c) d) ))) (cadr(cadr(cadr ’(a (b (c (d))))))) 15