#!/usr/bin/env racket
#lang racket
(provide unfoldTree foldTree)
(define (unfoldTree f b)
(match-let ((`(,a ,bs) (f b)))
`(,a ,(map (lambda (b)
(unfoldTree f b)) bs))))
(define (foldTree f tree)
(define (go node)
(match-let ((`(,x ,ts) node))
(f x (map go ts))))
(go tree))
(define (buildNode x)
(if (> (add1 (* 2 x)) 7)
`(,x ())
`(,x (,(* 2 x) ,(add1 (* 2 x))))))
;; 二分木の生成
(println (unfoldTree buildNode 1))
;; 木の値の総和
(println
(foldTree (lambda (x xs)
(apply + x xs)) '(1 ((2 ()) (3 ())))))
;; 木の最大値
(println
(foldTree (lambda (x xs)
(apply max x xs)) '(1 ((2 ()) (3 ())))))
;; 木の葉の個数
(println
(foldTree (lambda (x xs)
(if (null? xs)
1
(apply + xs))) '(1 ((2 ()) (3 ())))))
;; 木の高さ
(println
(foldTree (lambda (x xs)
(if (null? xs)
0
(add1 (apply max xs)))) '(1 ((2 ()) (3 ())))))
;; フィボナッチ数列
(define (fib n)
(define (g n)
(case n
((0) '(0 ()))
((1) '(1 ()))
(else `(,n (,(sub1 n) ,(- n 2))))))
(foldTree (lambda (x xs)
(if (null? xs)
x
(apply + xs))) (unfoldTree g n)))
(println (fib 5))
IyEvdXNyL2Jpbi9lbnYgcmFja2V0CiNsYW5nIHJhY2tldAoKKHByb3ZpZGUgdW5mb2xkVHJlZSBmb2xkVHJlZSkKCihkZWZpbmUgKHVuZm9sZFRyZWUgZiBiKQogIChtYXRjaC1sZXQgKChgKCxhICxicykgKGYgYikpKQogICAgYCgsYSAsKG1hcCAobGFtYmRhIChiKQogICAgICAgICAgICAgICAgICh1bmZvbGRUcmVlIGYgYikpIGJzKSkpKQoKKGRlZmluZSAoZm9sZFRyZWUgZiB0cmVlKQogIChkZWZpbmUgKGdvIG5vZGUpCiAgICAobWF0Y2gtbGV0ICgoYCgseCAsdHMpIG5vZGUpKQogICAgICAoZiB4IChtYXAgZ28gdHMpKSkpCiAgKGdvIHRyZWUpKQoKKGRlZmluZSAoYnVpbGROb2RlIHgpCiAgKGlmICg+IChhZGQxICgqIDIgeCkpIDcpCiAgICAgIGAoLHggKCkpCiAgICAgIGAoLHggKCwoKiAyIHgpICwoYWRkMSAoKiAyIHgpKSkpKSkKCjs7IOS6jOWIhuacqOOBrueUn+aIkAoocHJpbnRsbiAodW5mb2xkVHJlZSBidWlsZE5vZGUgMSkpCgo7OyDmnKjjga7lgKTjga7nt4/lkowKKHByaW50bG4KIChmb2xkVHJlZSAobGFtYmRhICh4IHhzKQogICAgICAgICAgICAgKGFwcGx5ICsgeCB4cykpICcoMSAoKDIgKCkpICgzICgpKSkpKSkKOzsg5pyo44Gu5pyA5aSn5YCkCihwcmludGxuCiAoZm9sZFRyZWUgKGxhbWJkYSAoeCB4cykKICAgICAgICAgICAgIChhcHBseSBtYXggeCB4cykpICcoMSAoKDIgKCkpICgzICgpKSkpKSkKCjs7IOacqOOBruiRieOBruWAi+aVsAoocHJpbnRsbgogKGZvbGRUcmVlIChsYW1iZGEgKHggeHMpCiAgICAgICAgICAgICAoaWYgKG51bGw/IHhzKQogICAgICAgICAgICAgICAgIDEKICAgICAgICAgICAgICAgICAoYXBwbHkgKyB4cykpKSAnKDEgKCgyICgpKSAoMyAoKSkpKSkpCgo7OyDmnKjjga7pq5jjgZUKKHByaW50bG4KIChmb2xkVHJlZSAobGFtYmRhICh4IHhzKQogICAgICAgICAgICAgKGlmIChudWxsPyB4cykKICAgICAgICAgICAgICAgICAwCiAgICAgICAgICAgICAgICAgKGFkZDEgKGFwcGx5IG1heCB4cykpKSkgJygxICgoMiAoKSkgKDMgKCkpKSkpKQoKOzsg44OV44Kj44Oc44OK44OD44OB5pWw5YiXCihkZWZpbmUgKGZpYiBuKQogIChkZWZpbmUgKGcgbikKICAgIChjYXNlIG4KICAgICAgKCgwKSAnKDAgKCkpKQogICAgICAoKDEpICcoMSAoKSkpCiAgICAgIChlbHNlIGAoLG4gKCwoc3ViMSBuKSAsKC0gbiAyKSkpKSkpCiAgKGZvbGRUcmVlIChsYW1iZGEgKHggeHMpCiAgICAgICAgICAgICAgKGlmIChudWxsPyB4cykKICAgICAgICAgICAgICAgICAgeAogICAgICAgICAgICAgICAgICAoYXBwbHkgKyB4cykpKSAodW5mb2xkVHJlZSBnIG4pKSkKCihwcmludGxuIChmaWIgNSkpCg==