WHEN, UNLESS — 조건에 따른 단순 실행 매크로
WHEN, UNLESS — 조건에 따른 단순 실행 매크로
'이 조건이 참일 때만 여러 폼을 실행하고 싶어요' 하는 경우가 아주 흔하죠. if는 then/else 두 갈래 모두 필요할 때 쓰고, 한쪽만 실행하고 싶을 때는 when과 unless가 훨씬 간결해요. when test는 참일 때, unless test는 거짓일 때 폼들을 실행해요. 이 문서는 매크로(macro) 문서예요.
본문
문법 (Syntax)
when test-form form* => result*
unless test-form form* => result*
인자와 값 (Arguments and Values)
test-form— form이에요.forms— implicit progn이에요.results—when폼에서test-form이 참이거나unless폼에서test-form이 거짓일 때forms의 값들이에요. 그 외에는nil이에요.
설명 (Description)
when과 unless는 하나의 test-form에 따라 forms의 실행 여부를 결정하게 해줘요.
when 폼에서는 test-form이 참이면 forms를 왼쪽에서 오른쪽으로 순서대로 평가하고, forms가 반환하는 값들을 when 폼에서 반환해요. test-form이 거짓이면 forms는 평가되지 않고 when 폼은 nil을 반환해요.
unless 폼에서는 test-form이 거짓이면 forms를 왼쪽에서 오른쪽으로 평가하고, forms가 반환하는 값들을 unless 폼에서 반환해요. test-form이 참이면 forms는 평가되지 않고 unless 폼은 nil을 반환해요.
예제 (Examples)
기본 동작과, 실행된 forms의 마지막 값이 반환되는 모습을 확인해 볼게요.
(when t 'hello) => HELLO
(unless t 'hello) => NIL
(when nil 'hello) => NIL
(unless nil 'hello) => HELLO
(when t) => NIL
(unless nil) => NIL
(when t (prin1 1) (prin1 2) (prin1 3))
>> 123
=> 3
(unless t (prin1 1) (prin1 2) (prin1 3)) => NIL
(when nil (prin1 1) (prin1 2) (prin1 3)) => NIL
(unless nil (prin1 1) (prin1 2) (prin1 3))
>> 123
=> 3
(let ((x 3))
(list (when (oddp x) (incf x) (list x))
(when (oddp x) (incf x) (list x))
(unless (oddp x) (incf x) (list x))
(unless (oddp x) (incf x) (list x))
(if (oddp x) (incf x) (list x))
(if (oddp x) (incf x) (list x))
(if (not (oddp x)) (incf x) (list x))
(if (not (oddp x)) (incf x) (list x))))
=> ((4) NIL (5) NIL 6 (6) 7 (7))
폼들이 실행되면 그중 마지막 값이 돌아오고, 실행되지 않으면 nil이 돌아와요.
부수 효과 (Side Effects)
없음.
영향받는 요소 (Affected By)
없음.
예외 상황 (Exceptional Situations)
없음.
더 알아보기 (See Also)
andcondifor
참고 (Notes)
when과 unless는 다음과 같은 폼들과 동등해요.
(when test {form}+) == (and test (progn {form}+))
(when test {form}+) == (cond (test {form}+))
(when test {form}+) == (if test (progn {form}+) nil)
(when test {form}+) == (unless (not test) {form}+)
(unless test {form}+) == (cond ((not test) {form}+))
(unless test {form}+) == (if test nil (progn {form}+))
(unless test {form}+) == (when (not test) {form}+)