;;1. checking the listp of (car input)
(defun deep-reverse (list)
(cond ((null list) nil)
((atom (car list))
(append (deep-reverse (cdr list))
(list (car list))))
(t (append (deep-reverse (cdr list))
(list (deep-reverse (car list))))))
;;2. checking the listp of input itself
(defun deep-reverse (list)
(cond ((null list) nil)
((atom list) (list list))
(t (append (deep-reverse (cdr list))
(deep-reverse (car list))))))
;the result of one deep-reverse call is always a list, so that in the recursive part they could be appended together. append is an amazing function that works like cells merging.
;;3. tail-recursive. so counter-intuitive. how?
;this is a simple reverse in tail recursive:
(defun reverse (list increment)
(cond ((null list) increment)
(t (reverse (cdr list)
(cons (car list) increment)))))
;the only time tail-recursive returns a value, is at it's end. at the clause "(null list)". how's this supposed to be recursive?
;THIS IS WRONG; i'll have to rethink about it.
(defun tail-recursive (list increment)
(cond ((null list) increment)
(t (tail-recursive (cdr list)
(cons (tail-recursive (car list)
increment)
increment)))))
;;4. someone else's solution, which used reverse:
(defun deep-reverse (list)
(if (consp list)
(reverse (mapcar #'deep-reverse list))
list))
;ultimately, it is applying the same rule to each element in the tree. just that it's a recursive one. It never occurred to me that "walk the tree" could be done with mapcar. this is beautiful.
Quote: Defining scale-list in terms of mapcar suppresses that level of detail and emphasises that scaling transforms a list of elements to a list of results. The difference between the two definitions is not that the computer is performing a different process (it isn't) but that we think about the process differently.
Amazing.
EXERCISE 2.27
EXERCISE 2.28
EXERCISE 2.29
EXERCISE 2.30-32
EXERCISE 2.33-34
EXERCISE 2.35
EXERCISE 2.36-37
EXERCISE 2.38-39
EXERCISE 2.40-41
EXERCISE 2.42-43
没有评论:
发表评论