牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

2.2.1 Representing Sequencesの『map』あたりをPythonでやってみた

SICP2.2.1 Representing Sequences の Mapping over lists
あたりを Python でやってみた


普通に実行するとエラーでるので少し手を加えてやってみた。

scheme
;Mapping over lists
;
;実行すると nil でエラーになるから
;; gosh> *** ERROR: unbound variable: nil
;; Stack Trace:
;; _______________________________________
;;   0  (scale-list (cdr items) factor)
;;         At line 34 of "(stdin)"
;;   1  (scale-list (cdr items) factor)
;;         At line 34 of "(stdin)"
;;   2  (scale-list (cdr items) factor)
;;         At line 34 of "(stdin)"
;;   3  (scale-list (cdr items) factor)
;;         At line 34 of "(stdin)"
;;   4  (scale-list (cdr items) factor)
;;         At line 34 of "(stdin)"
;
;空のリストは
;; gosh> (list)
;; ()
;みたいなので
;『nil』の部分を『()』に変えてやってみた
;
(define (scale-list items factor)
  (if (null? items)
      ();nil
      (cons (* (car items) factor)
            (scale-list (cdr items) factor))))
(scale-list (list 1 2 3 4 5) 10);(10 20 30 40 50)
;
(define (map proc items)
  (if (null? items)
      ();nil
      (cons (proc (car items))
            (map proc (cdr items)))))
(map abs (list -10 2.5 -11.6 17));(10 2.5 11.6 17)
(map (lambda (x) (* x x))
     (list 1 2 3 4));(1 4 9 16)
;Now we can give a new definition of scale-list in terms of map:
(define (scale-list items factor)
  (map (lambda (x) (* x factor))
       items))
(scale-list (list 1 2 3 4 5) 10);(10 20 30 40 50)
python
#Mapping over lists
def scale_list(items, factor):
    if not items:
        return []
    return [items[0] * 10] + scale_list(items[1:], factor)
print scale_list([1,2,3,4,5], 10) #[10, 20, 30, 40, 50]
#
def f_map(proc, items):
    if not items:
        return []
    return [proc(items[0])] + f_map(proc, items[1:])
print f_map(lambda x:abs(x), [-10,2.5,-11.6,17]) #[10, 2.5, 11.6, 17]
print f_map(lambda x:x * x, [1,2,3,4]) #[1, 4, 9, 16]
#Now we can give a new definition of scale-list in terms of map:
def scale_list_b(items, factor):
    return f_map(lambda x:x * factor, items)
print scale_list_b([1,2,3,4,5], 10) #[10, 20, 30, 40, 50]
#in usual python case
print map(lambda x:x * 10, [1,2,3,4,5])#[10, 20, 30, 40, 50]