SICPの2.2.2 Hierarchical Structures の Mapping over trees あたりを Python でやってみた
scheme
;2.2.2 Hierarchical Structures ;Mapping over trees (define (scale-tree tree factor) (cond ((null? tree) ()) ((not (pair? tree)) (* tree factor)) (else (cons (scale-tree (car tree) factor) (scale-tree (cdr tree) factor))))) (scale-tree (list 1 (list 2 (list 3 4) 5) (list 6 7)) 10) ;(10 (20 (30 40) 50) (60 70)) (define (scale-tree tree factor) (map (lambda (sub-tree) (if (pair? sub-tree) (scale-tree sub-tree factor) (* sub-tree factor))) tree)) (scale-tree (list 1 (list 2 (list 3 4) 5) (list 6 7)) 10) ;(10 (20 (30 40) 50) (60 70))
python
scheme の pair?の代用にとりあえず isinstance()をつかってみた。結構ハマった(´・ω・`)
type() でなくてisinstance() 推奨なのね...
#2.2.2 Hierarchical Structures #Mapping over trees def scale_tree(tree, factor): if not tree: return [] if not isinstance(tree, list): return tree * factor return [scale_tree(tree[0], factor)] + scale_tree(tree[1:], factor) print scale_tree([1,[2,[3,4],5],[6,7]], 10) #[10, [20, [30, 40], 50], [60, 70]] def scale_tree_lambada(tree, factor): return map(lambda sub_tree: isinstance(sub_tree, list) == True and scale_tree_lambada(sub_tree, factor) or sub_tree * factor, tree) print scale_tree_lambada([1,[2,[3,4],5],[6,7]], 10) #[10, [20, [30, 40], 50], [60, 70]]
う〜む、ややこしくなってきたかも。MITで使われてるだけはある?(||゚Д゚)
っていうか、まだ2章の初めなんだけどなぁ...何なの?馬鹿なの私?
予定では3章でわけわからなくなって(飽きてきて?)、4章あたりでサジ投げかける的な展開になると踏んでたのだが。甘く見てたかな(´・ω・`)