3장. 모듈, 객체, 상태
-
Modularity, Objects, and State
- 3장은, 상태를 도입하면 프로그램이 더 많은 것을 표현할 수 있지만, 그만큼 이해와 예측이 어려워지는 것을 설명.
-
변하는 데이터와 시간의 흐름을 다룸.
- 상태가 있는 시스템에서 시간과 동시성 문제는 필연적으로 등장.
- 상태를 안전하게 다루는 데에 있어 모듈성과 캡슐화는 필수.
- 지연 평가를 활용하면 무한 리스트나 신호 처리처럼 강력한 모델을 만들 수 있음.
기본
문법
;; ================
;; 셋팅
(set! a 10)
;;!> set!: assignment disallowed;
;;!> cannot set variable before its definition
;;!> variable: a
(define a 10)
(set! a 20)
a
;;=> 20
(define a-cons (cons 1 2))
a-cons
;;=> (1 . 2)
(set-car! a-cons 10)
(set-cdr! a-cons 20)
a-cons
;;=> (10 . 20)
;; ================
;; begin 블록
(begin ; 블록 구문. 맨 마지막 표현식이 반환값.
(display "Hello, ")
(display "world!")
(newline)
42)
;;>> Hello, world!
;;=> 42
cons-stream - (cons a (delay b))
delay - (delay exp)는 구문적 설탕입니다 .(lambda () exp)
force
Closure
- 함수가 정의될 때, 해당 함수가 속한 어휘적 환경(lexical environment) 에 대한 접근 권한을 유지하는 함수.
(define (new-counter initial-value)
(let ((curr (dec initial-value))) ; local state variable
(lambda ()
(set! curr (inc curr))
curr)))
(define counter (new-counter 1))
counterx)
;;=> 1
(counter)
;;=> 2
(counter)
;;=> 3
curr ; count-factory함수 밖에서는 curr접근 불가.
;;!> . . curr: undefined;
;;!> cannot reference an identifier before its definition
TODO
- Language Oriented Design - Discussing SICP with Hal Abelson
- 클래스 같은 추상화나 다양한 객체를 클래스로 어떻게 구성하는지, 그리고 그 전체적인 구조는 어떻게 되는지에 대해서는 전혀 언급하지 않았습니다
3.3 변형 가능한 데이터로 프로그래밍하기 3.3.1 변형 가능한 리스트 3.3.2 큐 queue/deque dictionary memoization - fibonacci
- https://clojuredocs.org/clojure.core/memoize
3.3.3 표 3.3.4 디지털 회로 시뮬레이터 3.3.5 관계 알리기(constraint propagation)
3.4 병행성竝行性 : 시간은 중요하다 은행의 출금을 예로들어 serializer
- 자원을 공유하는 함수들 끼리 그룹을 묶어, 그 구룹내에 있는 함수들은 동시에 실행이 안되게 막음.
- job queue같은걸 만들어 큐에 쌓고 순차적으로 실행.
parallel-execute - https://stackoverflow.com/questions/13467753/implement-parallel-execute-in-scheme
- mutex(Mutual Exclusion Lock)락을 이용해서 재화를 건드리는 함수들에 락을 걸어버림.
- 하나의 쓰레드만 자원 접근 가능
3.5 스트림
- stream == lazy sequence
- 지연 평가(lazy evaluation)를 통해 필요할 때만 다음 요소를 계산하는 시퀀스를 뜻합니다.
- ref
- https://clojuredocs.org/clojure.core/lazy-seq