Upgrade to Pro — share decks privately, control downloads, hide ads and more …

(call/cc (lambda (cont) (cont 知見)))

Susisu
October 18, 2015

(call/cc (lambda (cont) (cont 知見)))

call/cc の簡単な解説と実装の適当な紹介
http://connpass.com/event/20445/

Susisu

October 18, 2015
Tweet

More Decks by Susisu

Other Decks in Programming

Transcript

  1. ( c a l l / c c ( l

    a m b d a ( c o n t ) ( c o n t ஌ ݟ ) ) ) 2 0 1 5 ೥ 1 0 ݄ 1 8 ೔ ୈ 2 ճ O U C C LT ձ
  2. ͓ · ͑ ͔ • ͢͢͠ • ΞϨܥ • űwiűűer:

    @susisu2413 • GitHub: susisu • Scheme ૉਓͰ͢
  3. ܧ ଓ • "ܧଓʢ͚͍ͧ͘ɺcontinuationʣͱ͸ɺϓϩάϥϜͷ ࣮ߦʹ͓͍ͯ͋Δ࣌఺ʹ͓͍ͯධՁ͞Ε͍ͯͳ͍࢒Γ ͷϓϩάϥϜʢthe rest of the programʣΛҙຯ͢Δ΋

    ͷͰ͋Γɺखଓ͖ʢprocedureʣͱͯ͠දݱ͞ΕΔ΋ ͷͰ͋Δɻ" ܧଓ - Wikipedia https://ja.wikipedia.org/wiki/ %E7%B6%99%E7%B6%9A
  4. ϥϜ μ ࣜ Ͱ ͸ (lambda (x) (NEXT (+ 1

    x) )) NEXT ͸ͦ͜ͰධՁΛऴྃ͢ΔԾ૝ͷॲཧ
  5. c a l l / c c • ུͣ͞ʹݴ͏ͱ call-with-

    current-continuation • ݱࡏͷܧଓΛҾ਺ͱͯ͠, ༩͑ΒΕͨؔ਺Λݺͼग़͢ • ܧଓ͸ͨͩͷؔ਺ͳͷͰ, อଘ͓͍ͯͯ͠, ผͷ৔ॴ ͔Βݺͼग़͢͜ͱ΋Մೳ
  6. 2 Λ c a l l / c c ͷ

    ࣜ Ͱ ஔ ͖ ׵ ͑ͯ Έ Δ (+ 1 (call/cc (lambda (cont) (cont 2)) ))
  7. c a l l / c c ͷ Ҿ ਺

    ( ؔ ਺ ) ʹ ౉ ͞ Ε Δ ܧ ଓ (+ 1 (...))
  8. ͭ · Γ ͜͏ ͍ ͏ ͜ ͱ (+ 1

    ( (lambda (cont) (cont 2)) (lambda (x) (NEXT ( (+ 1 x) ))) ))
  9. 

  10. Կ ʹ ࢖ ͑Δ ͷ ͔ • ϧʔϓ୤ग़ (break) •

    ྫ֎ॲཧ (throw) • ίϧʔνϯ (yield) • return, goto, etc. • ཁ͸ಥೖͱ୤ग़
  11. Ͳ ͏ ͍ ͏ ࣮ ૷ • https://github.com/susisu/js-sandbox/blob/master/ continuation/src/v2.js •

    AST ΠϯλϓϦλ in JavaScript • جૅ͸લճͷ LT Ͱൃදͨ͠΋ͷͷྲྀ༻ http://susisu.hatenablog.com/entry/2015/07/12/142250 • Scheme ͷྫΛ͍͔ͭ͘ࢼͨ͠ͱ͜Ζظ଴௨Γʹಈ࡞ͨ͠ ͷͰɺͨͿΜ্ख͍͍ͬͯ͘Δ
  12. ܧ ଓ ͷ ੜ ੒ ( ୯ ७ Խ ͠

    ͨ ΋ ͷ ) • ࣜ Expr • ࣜͷධՁ eval : Expr → Res ― ݫີʹ͸؀ڥ΋ඞཁ • ධՁ݁Ռ Res = Ok Val ― ੒ޭ | Cont Val (Res → Res) ― ܧଓ | Next Val ― ධՁऴྃ
  13. ܧ ଓ ͷ ੜ ੒ • ྫ͑͹ɺෳ਺ͷࣜΛॱ൪ʹධՁ͢ΔΑ͏ͳࣜ e = (e1

    : Expr, e2 : Expr, ..., eN : Expr) : Expr r = eval e, ri = eval ei ― ධՁ݁Ռ • ri = Ok v 㱺 ei+1 Ҏ߱ͷධՁΛଓ͚Δ, i = N ͳΒ͹ r = Ok v • Cont f c 㱺 r = Cont f ((λx → eval ([r1 , ..., ri-1 ,] x, ei+1 , ..., eN )) ◦ c) • Next v 㱺 r = Next v
  14. ܧ ଓ ͷ ੜ ੒ • τοϓϨϕϧʹ͸த਎ͷࣜͷධՁ݁Ռ͕ Ok v ͳΒ͹

    Next v ͱͳΔࣜΛஔ͍͓ͯ͘ • eval “(call/cc f)” = Cont f (λx → x) • (call/cc f) ΛؚΉࣜΛධՁ͢Δͱ Cont f c ͕ಘΒΕΔ • ࠷ޙʹ c (f c) Λܭࢉ͢Ε͹ (ͦͷ͏ͪ) ஋͕ग़ͯ͘Δ
  15. ?