網頁

2018年5月28日 星期一

LISP Programming 1062_ex8

http://erdos.csie.ncnu.edu.tw/~klim/scheme/lisp-1062.html
exercise 8: enumerate a tree with sequence interface
•Rewrite (enum-tree T) with accumulate and map.

解答:
;enumerate tree
(define (enumerate-tree tree)
  (cond ((null? tree) '())
        ((not (pair? tree))
              (list tree))
        (else (append (enumerate-tree (car tree))
                      (enumerate-tree (cdr tree))))))
;use map list a tree to see ex2.30
;(1) map a tree
(define (lst x) (append x))
(define (map-tree t)
    (enumerate-tree
        (map (lambda (sub-tree)
             (if (pair? sub-tree)
                 (map-tree sub-tree)
                 (lst sub-tree)))
                t)))
(define nil '())

;p78 accumulate.scm
(define (accumulate op initial sequence)
    (if (null? sequence)
        initial
        (op (car sequence)
            (accumulate op initial (cdr sequence))))
)
;(2) accumulate a tree
(define (enum-tree t )
   (accumulate cons
               (list)         ;empty list
               (map-tree t)))
執行結果:
 
 

2018年5月21日 星期一

LISP Programming 1062_ex7

http://erdos.csie.ncnu.edu.tw/~klim/scheme/lisp-1062.html

exercise 7: mapping over trees
•Refer to exercise 2.31.
解答:
(define l (list 1 (list 2 3 (list 4 5))))

(define (sq x) (* x x))

(define (tree-map f tree)
  (cond ((null? tree)
          '())
        ((not (pair? tree))
          (f tree))
        (else
          (cons (tree-map f (car tree))
                (tree-map f (cdr tree))))))
執行結果:

2018年5月7日 星期一

LISP Programming 1062_ex6

http://erdos.csie.ncnu.edu.tw/~klim/scheme/lisp-1062.html
 
exercise 6: representing a pair with a number
•Refer to exercise 2.5.
•Note the requirement of nonnegative is removed. Your method 
should accept two integers.

解答:
(define (num-cons a b)
    (* (expt 2 a) (expt 3 b)))

(define (num-car n)
  (if (= 0 (modulo n 2))
      (+ 1 (num-car (/ n 2)))
      0))

(define (num-cdr n)
  (if (= 0 (modulo n 3))
      (+ 1 (num-cdr (/ n 3)))
      0))
執行結果: