Javascript使いもSICPを読むべき
Javascriptで名前空間を汚染しないようにクロージャを使うイディオム、例えばA JavaScript Module Patternって、
SICP第3章のコレじゃん。
3.1.1 Local State Variables
(define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch m) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch) (define acc (make-account 100)) ((acc 'withdraw) 50) 50 ((acc 'withdraw) 60) "Insufficient funds" ((acc 'deposit) 40) 90 ((acc 'withdraw) 60) 30
このSchemeをJavascriptで書くとこうなる。
function make_account(balance) { function withdraw(amount) { if (balance >= amount) { balance -= amount; return balance; } else return "Insufficient funds"; } function deposit(amount) { balance += amount; return balance; } return { withdraw: withdraw, deposit: deposit } }; var acc = make_account(100); acc.withdraw(50); 50 acc.withdraw(60); "Insufficient funds" acc.deposit(40); 90 acc.withdraw(60); 30
Javascriptは C言語構文の皮をかぶったSchemeなので、ぜひSICPを読むべきだと思う。読めばクロージャを完璧に理解できる。
Javascript1.7で let文やyieldや分割代入が入るので、これからますますSchemeっぽくなる。
Javascriptで学ぶSICPって書いたら面白そう。
l / ヽ / ヽ \ / / l ヽ / | \ し な 間 〉 // l_ , ‐、 ∨ i l | | \ 継 | ら っ に |/ l ,-、,/レ‐r、ヽ | /`K ,-、 < よ | ん て あ / | l``i { ヽヽ l | / , '/',` //`|_/ 続 | ぞ も わ |> ヽl´、i '_ 。`、llィ'。´ _/ /,) /\ こ | | な |`/\ヽ'_i ,.,.,.⌒´)_ `_⌒ /__/l \ を っ | く |/ / l´,.-― 、l`ー一'_冫 /l l | / せ !!!! | \ ', / /`7-、二´、,.| /// | / lT´ { / / ト、 |::| /// / / !!!!! l´ ヽ、 > ー ,/ |ニ.ノ-' / / _ i``` 、/ } ',,,..' |-'´,- '´  ̄/ ヽ∧ ____ (こいつはyieldだ! \/ ' \_ `´ノ7l´ / // ヽ l ヽ クソッタレー!) / ̄ |  ̄ ̄/ ノ L___/ ★ U | / ヽ /`ー´ /l |