Slide 1

Slide 1 text

Continuations in Ruby Antono Vasiljev Ruby Open Air, 2012

Slide 2

Slide 2 text

Continuation is basically Rest of the program

Slide 3

Slide 3 text

Continuations are first class objects in Ruby

Slide 4

Slide 4 text

irb(main)> c = callcc { |cont| cont } => #

Slide 5

Slide 5 text

Continuations are about Flow Control

Slide 6

Slide 6 text

1: i = 0 2: callcc do |cont| 3: i = 1 4: cont.call 5: i = 2 # skipped 6: end 7: 8: # i => 1

Slide 7

Slide 7 text

1: i = 0 2: i = callcc do |cont| 3: i = 1 4: cont.call(2) 5: i = 3 # skipped 6: end 7: 8: # i => 2 # See lines: 2, 4

Slide 8

Slide 8 text

1| i = 0 2| 3| label :sum 4| 5| puts i += 1 6| 7| goto :sum, cond: (i < 10)

Slide 9

Slide 9 text

1| LABELS = {} 2| 3| def label(name) 4| callcc { |cont| LABELS[name] = cont } 5| end 6| 7| def goto(label, args: {}) 8| LABELS[label].call if args[:cond] 9| end

Slide 10

Slide 10 text

Continuation are like goto with parameters (but jumps only backward)

Slide 11

Slide 11 text

continuations jumps far def foo bar end def bar baz end def baz $cont[0] end callcc { |c| $cont = c; foo }

Slide 12

Slide 12 text

Similar to exceptions. But can go down through stack. Time Machine!

Slide 13

Slide 13 text

Restartable Exceptions

Slide 14

Slide 14 text

1| begin 2| hello 3| rescue Exception => e 4| e.restart 5| ensure 6| e.cleanup 7| end

Slide 15

Slide 15 text

1| def hello 3| i = 0 4| restartable do 5| puts i += 1 6| raise Exception unless i == 5 7| end 8| end

Slide 16

Slide 16 text

1| def restartable 2| cont = callcc { |c| c } 3| begin 4| yield 5| rescue Exception => e 6| e.continuation = cont 7| raise e 8| end 9| end

Slide 17

Slide 17 text

require 'continuation' class Exception class << self attr_accessor :conts end def continuation=(cont) self.class.conts ||= {} self.class.conts[self.class] ||= cont end

Slide 18

Slide 18 text

def restart self.class.conts[self.class].call end def cleanup self.class.conts.delete(self.class) end end

Slide 19

Slide 19 text

You can do with continuation: Generator objects Fibers/Coroutines Exit from recursion Other control structures

Slide 20

Slide 20 text

Thanks!

Slide 21

Slide 21 text

http://antono.info/