square-list 구현 (SICP 138쪽) 학술

연습문제 2.22. 재귀적으로 square-list 구현.
(define (square-list items)
  (if (null? items)
      '()
      (cons (expt (car items) 2)
            (square-list (cdr items)))))

> (square-list (list 1 2 3 4 5))
(1 4 9 16 25)
연습문제 2.22. 반복적으로 square-list 구현했을 때 순서가 뒤집혀서 나온다.
(define (square-list items)
  (define (iter things answer)
    (if (null? things)
        answer
        (iter (cdr things)
              (cons (expt (car things) 2)
                    answer))))
  (iter items '()))
> (square-list (list 1 2 3 4))
(16 9 4 1)

아래처럼 뒤집어봤자,
(define (square-list items)
  (define (iter things answer)
    (if (null? things)
        answer
        (iter (cdr things)
              (cons answer
                    (expt (car things) 2)))))
  (iter items '()))
결과는 더 이상하게 나올 뿐이다 ㅋㅋ
> (square-list (list 1 2 3 4))
((((() . 1) . 4) . 9) . 16)

원본 리스트에서 Head를 떼어 출력 리스트에 Head로 붙이는데 순서가 뒤집힐 수 밖에;

트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://xeraph.com/tb/4031286 [도움말]

핑백

덧글

댓글 입력 영역