Code Blocks, Closures, and Continuations

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
More about Ruby Maciej Mensfeld Presented by: Maciej Mensfeld More about Ruby dev.mensfeld.pl github.com/mensfeld.
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
C Language.
Principles of programming languages 4: Parameter passing, Scope rules Department of Information Science and Engineering Isao Sasano.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Chapter 2 Writing Simple Programs
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
A First Program Using C#
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
SYST Web Technologies SYST Web Technologies Lesson 6 – Intro to JavaScript.
Ruby and the tools 740Tools05ClassesObjectsVars Topics Ruby Classes Objects Variables Containers Blocks Iterators Spring 2014 CSCE 740 Software Engineering.
Ruby on Rails. What is Ruby? Programming Language Object-oriented Interpreted.
Introduction to Ruby WING Group Meeting 9 Jun 2006 Min-Yen Kan WING Group Meeting 9 Jun 2006 Min-Yen Kan.
Introduction to programming in the Java programming language.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Python Functions.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
RUBY by Ryan Chase.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
Functions Functions, locals, parameters, and separate compilation.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Introduction to information systems RUBY dr inż. Tomasz Pieciukiewicz.
PROGRAMMING USING PYTHON LANGUAGE ASSIGNMENT 1. INSTALLATION OF RASPBERRY NOOB First prepare the SD card provided in the kit by loading an Operating System.
CS314 – Section 5 Recitation 9
Chapter 2 Writing Simple Programs
Motivation for Generic Programming in C++
Object Lifetime and Pointers
Functions + Overloading + Scope
Test 2 Review Outline.
Review 1.
EEE 161 Applied Electromagnetics
Programming Languages Dan Grossman 2013
Ruby Getting started & Ruby.New Presented by Mario Tayah
Ruby: An Introduction Created by Yukihiro Matsumoto in 1993 (named after his birthstone) Pure OO language (even the number 1 is an instance of a class)
Learning to Program D is for Digital.
A bit of C programming Lecture 3 Uli Raich.
Python Let’s get started!.
Introduction to Python
Control Flow Constructs: Conditional Logic
Java Programming: Guided Learning with Early Objects
Principles of programming languages 4: Parameter passing, Scope rules
Functions, locals, parameters, and separate compilation
Topic: Functions – Part 2
JavaScript Syntax and Semantics
Programming Language Concepts (CIS 635)
Scripts & Functions Scripts and functions are contained in .m-files
JavaScript: Functions.
Classes, Objects, And Variables
Intro to PHP & Variables
Chapter 14 Introduction to Ruby.
Python Primer 2: Functions and Control Flow
Java Programming Language
Use of Mathematics using Technology (Maltlab)
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Ruby Testing 2, 11/9/2004.
T. Jumana Abu Shmais – AOU - Riyadh
Closure Closure binds a first-class function and a lexical environment together This is a complex topic, so we will build up our understanding of it we.
Ruby and the tools 740Tools05ClassesObjectsVars
CISC101 Reminders All assignments are now posted.
Ruby Containers, Iterators, and Blocks
Java Programming with BlueJ Objectives
COMPUTER PROGRAMMING SKILLS
Threads and concurrency / Safety
Presentation transcript:

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

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

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

Getting Started Ruby documentation What did we learn http://www.ruby-doc.org Using the ri tool What did we learn

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

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

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

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

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

Classes in ruby Demo of a class

More ruby syntax Containers Code blocks Iterators

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]

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

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

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}

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}

New concepts in ruby Closures Continuations Dynamic manipulations

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

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

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))

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

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)

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}

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

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

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

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

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}

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

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”

Done Final demo Any Questions

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