이 문제는 연습문제 2.38에서 나온 fold-right와 fold-left 프로시저로
연습문제 2.18에 나온 reverse 프로시저를 만드는 문제입니다.

둘 다 제대로 작동하네요.^^
fold-right를 이용하는 프로시저는 append 프로시저를 이용하는 것으로 하였습니다.
연습문제 2.33에서 append 프로시저를 accumulate 프로시저로 만들었기에
여기에 맞춰 조금 변형시켰습니다.
참조
해럴드 애빌슨, 김재우 역, <컴퓨터 프로그램의 구조와 해석>, 인사이트, 2007, pp. 159
; fold-left
(define (fold-left op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))
; fold-right = accumulate
(define (fold-right op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(fold-right op initial (cdr sequence)))))
; append
(define (append list1 list2)
(if (null? list1)
list2
(cons (car list1) (append (cdr list1) list2))))
; answer
(define (reverse-r sequence)
(fold-right (lambda (x y) (fold-right cons (list x) y)) null sequence))
; (fold-right cons (list x) y) 대신 (append y (list x))을 써도 된다.
(define (reverse-l sequence)
(fold-left (lambda (x y) (cons y x)) null sequence))
; execute
(reverse-r (list 1 4 9 16 25))
(reverse-l (list 1 4 9 16 25))
(reverse-r (list 1 3 5 7 9 11 13 15 17 19 21))
(reverse-l (list 1 3 5 7 9 11 13 15 17 19 21))
- SICP Exercise 연습문제 2.44 (0)2008/02/17
- SICP Exercise 연습문제 2.41 (0)2008/02/16
- SICP Exercise 연습문제 2.40 (0)2008/02/16
- SICP Exercise 연습문제 2.39 (0)2008/02/11
- SICP Exercise 연습문제 2.38 (0)2008/02/11
- SICP Exercise 연습문제 2.37 (0)2008/02/11
- SICP Exercise 연습문제 2.36 (0)2008/02/11
글에 잘못된 점, 다른 점, 부족한 점이 있다면 지적해주세요.
댓글, 트랙백, 메일 모두 고맙습니다.







댓글을 달아 주세요