728x90
1. Updating a variable
(defvar *total-glasses* 0)
(defun sell (n)
"전역 변수 사용"
(setf *total-glasses* (+ *total-glasses* n))
(format t "~&Total ~S glasses." *total-glasses*))
- total-glasses 라는 전역변수를 선언하고, sell이라는 함수로 전역 변수의 값을 바꿔준다.
- 변수의 값을 변경시키는 방법은 보통 3가지가 있다.
ⓐ (setf NumVar (+ NumVar 5))
ⓑ (incf NumVar 5)
ⓒ (decf NumVar)
2. Destructive Operations
1) Destructive Operations는 값을 변경 시켜주는 오퍼레이션이다.
- nonappend Destructive Operations에 append가 있다.
* append : x의 리스트에 y의 리스트를 추가하는 함수
>(setf X ‘(a b c))
>(setf Y ‘(d e f))
위와 같이 x와 y리스트를 선언했다고 하자.
>(append X Y)
>x => (a b c)
append를 하고 x를 출력해도, x는 원래의 리스트가 나오게 된다.
반면, NCONC: a destructive version of APPEND(append의 파괴적인버전) 은 변수의 값을 변경시킨다.
(nconc X Y)
> x => (a b c d e f)
※ 예외 : x가 nil일 때, 값이 바뀌지 않는다.
- 그 외의 Destructive Operations
ⓐ NSUBST: a destructive version of SUBST
* SUBST : 리스트의 원소를 교체한다. (바꿔진 원소, 바꿀 원소, 리스트)
(setf Tree ‘(I say (e I (e I) o)))
(nsubst ‘a ‘e Tree) ;; e -> a
(nsubst ‘cheery ‘(a I) Tree :test #’equal)
* #'equal을 사용하는 이유 : 주소를 비교하지 않고 값만 비교하기 위해서(리스트는 주소를 비교함)
- 활용
(defvar *Things*
'((object1 large green shiny cube)
(object2 small red dull metal cube)))
(defun rename (Obj NewName)
"전역 변수 사용"
(setf (car (assoc Obj *Things*)) NewName))
(defun addProperty (Obj Property)
"destructive operation 예제"
(nconc (assoc Obj *Things*) (list Property)))
728x90
'Major > Lisp' 카테고리의 다른 글
[Lisp] Chapter 12 구조체(Structures) (0) | 2021.06.09 |
---|---|
[Lisp] Tic-Tac-Toe 게임 실습(1) (0) | 2021.06.09 |
[Lisp] Ch 9 - Input/Output (0) | 2021.06.01 |
[Lisp] CH 8 - Recursion(재귀) (0) | 2021.06.01 |
[Lisp] Ch 7 Applicative Programming(실용적인 프로그래밍) (0) | 2021.05.29 |