무냐의 개발일지
[OSSU] <UBCx HtC1x_How to Code> / 7b_Local (encapsulation) 본문
[OSSU] <UBCx HtC1x_How to Code> / 7b_Local (encapsulation)
무냐코드 2024. 5. 7. 22:40학습목표
ENCAPSULATION !! PROGRAM EFFICIENCY
- Be able to write well-formed local expressions.
- Be able to diagram lexical scoping on top of expressions using local.
- Be able to hand-evaluate local expressions.
- Be able to use local to encapsulate function definitions.
- Be able to use local to avoid redundant computation.
Local Expression : 특정 코드 안에서만 정의되는 코드
rkt는 Intermediate으로 업그레이드됐다!!
(local [(define a 1)
(define b 2)]
(+ a b))
(local [(define p "accio")
(define (fetch n) (string-append p n))]
(fetch "portkey"))
>> 3
>> "accioportkey"
local 안에서만 a, b, p, fetch 가 정의된 상태임
형태 : (local [] ())
The local must have two parts, definitions and body.
We can have zero or more definitions in the square brackets,
but all definitions must be inside the square brackets.
| Lexical Scoping
국지적으로 범위를 제한하는 local
(define p "incendio ")
(local [(define p "accio")
(define (fetch n) (string-append p n))]
(fetch "portkey"))
since the closest p is "accio" , the result is "accioportkey"
1.Rename
2.Lift definition to the top level
3. Replace the local with its body
| Encapsulation
2명의 프로그래머가 전혀 다른 역할을 하지만, 이름이 같은 함수를 만들면??
혼란스럽겠지
그래서 생긴 게 encapsulation!!! 함수들을 다 local로 넣어버리는거다. 그 안에서만 작동할 수 있도록!
body에 해당하는 맨 마지막 (sum-data--element e) 이 줄을 trampoline이라고 한다
보잉ㅇ~~~ 해서 다시 위로 튕겨서 다른 함수로 들어간다고 해서 ㅋㅋ
(define (names-under-20 p)
(local [(define (names-under-20--person p)
(if (< (person-age p) 20)
(cons (person-name p)
(names-under-20--lop (person-children p)))
(names-under-20--lop (person-children p))))
(define (names-under-20--lop lop)
(cond [(empty? lop) empty]
[else
(append (names-under-20--person (first lop))
(names-under-20--lop (rest lop)))]))]
(names-under-20--person p)))
요런식으로 local 안에 그동안 주구장창 해왔던 코드를 넣어주는거다. 그러면 local에서는 다른 프로그래머와 겹칠 걱정 하지 않고, 내 맘대로 아무 이름이나 쓸 수 있다.
| Avoiding Recomputation
Local expressions can be used to avoid recomputing results, and in recursive programs this can have significant (even exponential) effects on program performance.
(define (find n e)
(local [(define (find--element n e)
(if (string=? (elt-name e) n)
(elt-data e)
(find--loe n (elt-subs e))))
(define (find--loe n loe)
(cond [(empty? loe) false]
[else
(local [(define try (find--element n (first loe)))]
(if (not (false? try))
try
(find--loe n (rest loe))))]))]
(find--element n e)))
Recursion 때문에, computing 시간이 exponentially increase 한다.
하지만 local 을 이용하면 훨씬 짧아진다.