LOCALLY 특수 연산자

LOCALLY 특수 연산자 (locally)

locally는 Common Lisp의 특수 연산자로, 주어진 선언(declaration)들이 효과를 갖는 어휘 환경(lexical environment)에서 몸체 폼들을 순차적으로 평가해요. declare를 특정 코드 지점에 한정해 적용할 때 쓰는 도구예요.

출처: CLHS: Special Operator LOCALLY

문법 (Syntax)

locally declaration* form* => result*

인자와 값 (Arguments and Values)

  • declarationdeclare 표현식이며, 평가되지 않아요.
  • forms — 암시적 progn이에요.
  • resultsform들의 값이에요.

설명 (Description)

주어진 선언들이 효과를 갖는 어휘 환경에서 몸체 폼들을 순차적으로 평가해요.

예제 (Examples)

 (defun sample-function (y)             ;this y is regarded as special
   (declare (special y)) 
   (let ((y t))                         ;this y is regarded as lexical
     (list y
           (locally (declare (special y))
             ;; this next y is regarded as special
             y))))
=> SAMPLE-FUNCTION
 (sample-function nil) => (T NIL) 
 (setq x '(1 2 3) y '(4 . 5)) => (4 . 5)
;;; The following declarations are not notably useful in specific.
;;; They just offer a sample of valid declaration syntax using LOCALLY.
 (locally (declare (inline floor) (notinline car cdr))
   (declare (optimize space))
   (floor (car x) (cdr y))) => 0, 1

이 첫 예시가 핵심을 보여줘요. let이 만든 y는 어휘 변수인데, locally 안에서 (declare (special y))를 쓰면 그 안의 y 참조만 특별 변수(special)로 취급돼요. 그래서 바깥 y(lexical t)와 locally 안쪽 y(special nil)가 다르게 평가돼요.

;;; This example shows a definition of a function that has a particular set
;;; of OPTIMIZE settings made locally to that definition.
 (locally (declare (optimize (safety 3) (space 3) (speed 0)))
   (defun frob (w x y &optional (z (foo x y)))
     (mumble x y z w)))
=> FROB
;;; This is like the previous example, except that the optimize settings
;;; remain in effect for subsequent definitions in the same compilation unit.
 (declaim (optimize (safety 3) (space 3) (speed 0)))
 (defun frob (w x y &optional (z (foo x y)))
   (mumble x y z w))
=> FROB

두 번째 예시는 locallydefun 정의 하나에 최적화 설정을 한정할 때 쓰는 모습이에요. 아래 declaim 버전은 그 설정이 같은 컴파일 단위 안의 이후 정의들에도 계속 남는다는 차이가 있어요.

부수 효과 (Side Effects)

없음.

영향 (Affected By)

없음.

예외 상황 (Exceptional Situations)

없음.

함께 보기 (See Also)

  • declare

참고 (Notes)

special 선언은 locally와 함께 쓰면 변수의 바인딩이 아니라 변수에 대한 참조에 영향을 줄 수 있어요.

locally 폼이 최상위 폼이면, 몸체 폼들도 최상위 폼으로 처리돼요. Section 3.2.3 (File Compilation)을 보세요.

더 알아보기 (Learn more)