Presentation is loading. Please wait.

Presentation is loading. Please wait.

Code Blocks, Closures, and Continuations

Similar presentations


Presentation on theme: "Code Blocks, Closures, and Continuations"— Presentation transcript:

1 Code Blocks, Closures, and Continuations
Presented by: Bassem ELkarablieh

2 Outline Getting Started with ruby Some ruby syntax Ruby classes
More ruby syntax New concepts in ruby

3 Getting Started Ruby is a dynamic, fully object-oriented scripting language. Installing ruby: One click windows installation (takes 5 min to setup ruby) Running ruby Interactive ruby (irb) Batch ruby (run program files)

4 Getting Started Ruby documentation What did we learn
Using the ri tool What did we learn

5 Some ruby Syntax Ruby is fully OO Variable definition
Every thing is an object (even literals) “hello”.length “bassem”.index(“e”) -88.abs Variable definition Number = 5 Number = “5” Number = “five” Delimiters: no ending ”;” is required

6 Some ruby Syntax Simple I/O Conditions
Puts: write the value to the output with new line character appended Gets: reads the value from standard input A = gets puts “Hello I am “ + A Conditions If else blocks If A>8 puts “greater” Else Puts “smaller” end

7 Some ruby Syntax Looping Control structures While block
While line = gets Puts line.uppercase End For … In blocks For I in 1..7 Print I, “ “ Control structures Break, redo, next , retry

8 Some ruby Syntax Assignment Parallel Assignment Method definition
a = b = 1+2+3 Instrument = “piano” Instrument [“ano”] = “ccolo” Parallel Assignment a,b = 6,7 Method definition def my_method(arg1,arg2,arg3) #this is a comment and code Def What did we learn

9 Classes in Ruby Initializer Instance variable Class variables
Instance methods Class methods Attributes operators Access controls

10 Classes in ruby Demo of a class

11 More ruby syntax Containers Code blocks Iterators

12 Containers Arrays Indexing an array A= [56,”hello”,99.66,”ll”]
B=Array.new Un-initialized members of an array are set to nil Indexing an array A[0] ->56 , A[-1] =“ll” A[1,1] ->[“hello”] A[0..2]-> [56,”hello”,99.66]

13 Containers Hashes H ={‘dog’=>’canine’, ‘cat’ => ’feline’, ’bird’ => ‘duck’} H.length => 3, h[‘dog’] =>’canine’ H[12] = ‘hello’, H[‘cat’] =99

14 Code Blocks Chucks of code that can be associated with method invocations Great methods for implementing callbacks Great tool for implementing iterators Code blocks are flexible , and can be passed parameters Great tool for implementing closures and continuations

15 Code Blocks Code block can be stored between{} or between do…end blocks Def my_method puts “hello” yield End my_method{puts “world”} Code block parameters differ from method parameters Def say_goodnight(name) puts “good night, #{name}” Yield (“sweet dreams”) Say_goodnight(“bassem”){|i| print i}

16 Iterators Built in iterators in ruby uses code block to support general plug-in architecture Examples 5.times{print “*”} 3.upto(6) {|i| print i} (‘a’..’z’).each{|char| print char} [‘cat’,’dog’,’horse’].each{|name| print name} [1,3,5,7,9].find{|v| v*v>3} [“H”,”A”,”L”].collect{|x| x.succ} [1,3,5,7].inject(0){|sum,element| sum+element}

17 New concepts in ruby Closures Continuations Dynamic manipulations

18 Closures A closure is a function created by a program at run time. This idea is written as a function that appears entirely within the body of another function. The nested, inner function may refer to local variables of the outer function. A closure can be used to represent a delayed user defined behavior that can be passed around in methods and objects

19 Closures Closure simulations
C: function pointers, void* parameters C++: Functors C# and java: Anonymous classes and methods Ruby have a special built-in Proc class that simplifies implementing closures

20 Proc Class Proc objects are blocks of code that have been bound to a set of local variables, once bound the code can be called from different context. Example: Def gen_times(factor) return Proc.new{|n| n*factor} End Times3 = gen_times(3) Times5 = gen_times(5) Times3.call(12) Times5.call(3) Times3.call(times5.call(4))

21 Proc Objects Proc objects can be created by associating a code block with it Example Def proc_from Proc.new End Proc = proc_from{“hello”} Proc.call

22 Code blocks as closures
Example1 Def n_times (thing) Return lambda {|n| thing*n} End # here lambda returns a Proc object associated with the code block P1 = n_times(23) P1.call(3) P2 = n_times(“hello”) P2.call(4)

23 Code blocks as closures
Example2 Songlist = SongList.new Class JukeboxButton<Button Def initialize(label,&action) Super(label) @action = action End Def button_pressd @action.call(self) Start_button = JukeboxButton.new(“start”){songlist.start} pause_button = JukeboxButton.new(“pause”){songlist.pause}

24 Continuations Continuations are objects that lets you save system state, and then return to that state on command Code blocks defines the universe in a continuation

25 Continuations A continuation object saves the execution state( mainly the execution stack) A continuation is created using a call to a Kernel method “callcc” which associates a continuation to a code block Similar to Proc object , continuations are triggered using a “call” method

26 Callcc method Generates a continuation object , which it passes to the associated block Performing a cont.call will use the callcc to return The value returned by callcc is the value of the block or the value passed to cont.call

27 Continuations Example1 Calloc do|cont| For i in 0..4 print “\n#{i}:”
for j in i*5 … (i+1)*5 cont.call() if (j==7) print j end End

28 Continuation Objects Callcc return values implicitly
Callcc{|cont| cont.call} Callcc{|cont| cont.call 1} Callcc{|cont| cont.call 1,2,3} Callcc return values Explicitly Callcc{|cont| return cont}

29 Continuations Example2 Def strange calloc {|cont| return cont}
print “back to method” End Print “before method” Temp = strange() Print “after method” If( Temp) Temp.call

30 Continuations Example3 Def loop for i in 1..5 puts I
callcc{|cont| return cont} if i==2 end return nil End Puts “before loop” Temp = loop() Puts “after loop call” If( Temp) Temp.call Puts “after continuation call”

31 Done Final demo Any Questions

32 What's next in ruby Ruby types Ruby methods Ruby Expressions


Download ppt "Code Blocks, Closures, and Continuations"

Similar presentations


Ads by Google