Continuation이란건 Sebesta 의 Programming Language 이후에 처음보네요.
def print_num for i in (1..10) puts i if i % 2 == 0; callcc{|c| return c}; end puts "** cont.call brings you here" # 물론 cont는 call 시 여기로 옵니다. end return nil end cont = print_num # cont 에는 이 사실도 저장됨 puts "Yae, I love even~" cont.call if cont puts "Bye"
실행결과는 다음과 같습니다.
C:\WINDOWS\system32\cmd.exe /c ruby a.rb
1
** cont.call brings you here
2
Yae, I love even~
** cont.call brings you here
3
** cont.call brings you here
4
Yae, I love even~
** cont.call brings you here
5
** cont.call brings you here
6
Yae, I love even~
** cont.call brings you here
7
** cont.call brings you here
8
Yae, I love even~
** cont.call brings you here
9
** cont.call brings you here
10
Yae, I love even~
** cont.call brings you here
Yae, I love even~
Bye
Hit any key to close this window…
이게 굉장히 헷갈리기가 쉬운데.. cont=print_num을하고 print_num안에서 callcc 로 closure를 만들때 print_num 을 호출하는 부분 역시 저장됩니다. 즉, “cont=print_num”을 했다는 사실과 print_num안에서의 컨텍스트가 저장되죠. 따라서 cont.call은 코드는 하나있지만 되지만 실행은 여러번 됩니다.
Leave a Reply