갈루아의 반서재



Nested Lists


리스트는 리스트를 포함할 수 있다. 예를 들면 다음과 같다. 이 경우 3개의 아이템을 가진 리스트가 된다. 두 번째 아이템은 (duck bat) 으로 그 자체가 리스트이다. 

1
2
[42]> '(cat (duck bat) ant)
(CAT (DUCK BAT) ANT)
cs

중첩리스트도 콘셀을 이용해서 구성된 것이며, 앞서 언급한 리스트 함수들을 이용하여 아래와 같이 원하는 아이템을 추출해낼 수 있다.

1
2
3
4
5
6
[43]> (car '((peas carrots tomatoes)(pork beef chicken)))
(PEAS CARROTS TOMATOES)
[43]> (cdr '(peas carrots tomatoes))
(CARROTS TOMATOES)
[43]> (cdar '((peas carrots tomatoes)(pork beef chicken)))
(CARROTS TOMATOES)
cs

cons 명령만 이용하여 아래와 같이 중첩리스트를 만들 수도 있다.

1
2
[44]> (cons (cons 'peas (cons 'carrots (cons 'tomatoes ()))) (cons (cons 'pork (cons 'beef (cons 'chicken ()))) ()))
((PEAS CARROTS TOMATOES) (PORK BEEF CHICKEN))
cs

car 과 cdr 을 위의 중첩리스트에 적용해보면 다음과 같다.

1
2
3
4
5
6
7
8
[45]> (cddr '((peas carrots tomatoes) (pork beef chicken) duck))
(DUCK)
[45]> (caddr '((peas carrots tomatoes) (pork beef chicken) duck))
DUCK
[45]> (cddar '((peas carrots tomatoes) (pork beef chicken) duck))
(TOMATOES)
[45]> (cadadr '((peas carrots tomatoes) (pork beef chicken) duck))
BEEF
cs

위에서 보듯이 c*r 와 같은 형태로 4단계까지 함수를 만들어 사용할 수 있다. 5단계를 적용하면 아래와 같이 undefined function 에러가 난다. 

1
2
3
4
5
6
7
8
[46]> (cadadr '((peas carrots tomatoes) (pork (beef turkey) chicken) duck))
(BEEF TURKEY)
[46]> (cdadadr '((peas carrots tomatoes) (pork (beef turkey) chicken) duck))
 
*** - EVAL: undefined function CDADADR
[47]> (caadadr '((peas carrots tomatoes) (pork (beef turkey) chicken) duck))
*** - EVAL: undefined function CAADADR
cs