CSC/ECE 517 Fall 2011/ch3 4b js
Closures
What is a Closure?
A closure is a block of code that can access the lexical environment of its definition. A closure has two properties:
- A closure can be passed as an object.
- A closure recalls the values of all the variables that were in scope when the function was created and is able to access those variables when it is called even though they may no longer be in scope.
A closure can be expressed succintly as a function pointer that references a block of executable code and the variables from the scope it was created.
Closures in Ruby
Ruby supports closures through use of Procedures, or simply procs, and lambdas, which are blocks.
Blocks
In Ruby, blocks are used to group statements usually enclosed by braces or between a do...end and occur solely in the source adjacent to a method call. Rule of thumb in Ruby is to use braces for blocks containing only a single line and do...end for multi-line blocks. The code within the block is not executed when encountered, instead, Ruby recalls the context of the block and then enters the method. Typically, the blocks passed into methods are anonymous objects that are created instantly, but they can be instantiated as a Proc object by using either the proc or lambda method. Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.(7) Proc objects can be simply thought of as anonymous function objects. Proc objects can be stored, created at runtime, passed as arguments, retrieved, as well as, be returned as values. Consider the example below from lecture 5:
Class to generate adders:
class AdderGen def initialize(n) @block = lambda {|a| n + a } end def add(a) @block.call a end end twoAdder = AdderGen.new 2 incrementer = AdderGen.new 1 puts incrementer.add(4) puts twoAdder.add(6)
>> 5 >> 8
In the example above, the instance variable @block is a closure and it recalls the parameter from which the initialize method was called after the initialize method exits and it is used when the block is called in the add method. This example also uses the lambda method to generate new functions dynamically, which will be discussed in the next section.
Procs and Lambdas
When creating a lambda or proc, the object holds a reference to the executable block and bindings for all the variables used by the block. In Ruby, we can create a Proc object explicitly in three different ways:
Proc.new
Using this method involves simply passing in a block, which will return a Proc object that will run the code in the block when you invoke its call method.
pobject = Proc.new {puts “This is a proc object.”} pobject.call
proc method
In the Kernel module, we can use the proc method, which is available globally. In Ruby 1.9, it is equivalent to Proc.new, but in Ruby 1.8, it is equivalent to lambda. The difference between proc and lambda will be discussed later.
pobject = proc { puts “Inside the proc object” } pobject.call
lambda method
Similar to the proc method, it is globally available in the Kernel module, however, it will create a lambda Proc object.
pobject = lambda { puts “Inside the proc object” } pobject.call
procs vs. lambdas
One difference between the proc kernel method and the lambda kernel method is that the lambda kernel method re \\esults in an object that checks the number of its arguments, while a plain Proc.new does not: Another difference between procs and lambdas is their handling of control flow keywords, such as break and return. Consider the examples below (1). For instance, the first example below shows the difference in behavior using the return keyword. With the proc method, the return not only returns from the proc method, but also the enclosing method, which is shown when the last puts is not called.
def my_method puts "before proc" my_proc = Proc.new do puts "inside proc" return end my_proc.call puts "after proc" end my_method
user@user-ubuntu:/home/user/ruby$ ruby a.rb before proc inside proc
If we exchange the proc for the lambda method, the return only returns from the lambda method and NOT the enclosing method, thus, it continues on to execute the last puts .
def my_method puts "before proc" my_proc = lambda do puts "inside proc" return end my_proc.call puts "after proc" end my_method
user@user-ubuntu:/home/user/ruby$ ruby a.rb before proc inside proc after proc
If we go back to the proc method, and use the break keyword in lieu of return . However, instead of returning from the proc method and the enclosing method, we are issued a LocalJumpError . Since break keywords are usually used to fall out of an iteration, but it is not contained within an iteration, Ruby throws an error.
def my_method puts "before proc" my_proc = Proc.new do puts "inside proc" break end my_proc.call puts "after proc" end my_method
user@user-ubuntu:/home/user/ruby$ ruby a.rb before proc inside proc a.rb:64:in `block in my_method': break from proc-closure (LocalJumpError) from a.rb:66:in `call' from a.rb:66:in `my_method' from a.rb:70:in `<main>'
Let us revisit the lambda method, but this time, we will use the break keyword. You will notice that the break is treated like the return keyword, where the execution is dumped out of the lambda, but continues to execute the rest of the enclosing method.
def my_method puts "before proc" my_proc = lambda do puts "inside proc" break end my_proc.call puts "after proc" end my_method
user@user-ubuntu:/home/user/ruby$ ruby a.rb before proc inside proc after proc
Why use Closures?
Closures not only enable programmers to write logic with less code, they are also useful in iterating over lists and encapsulation operations that require setup and clean-up afterwards.
Currying
Currying is a concept in Functional Programming that’s enabled by Higher-order functions. It is the technique of transforming a function that takes multiple arguments (or an n-tuple of arguments) in such a way that it can be called as a chain of functions each with a single argument (partial application).
Given a function f of type
f:(X x Y)-->Z
Currying it makes a function
curry(f): X-->(Y-->Z)
That is curry(f) takes an argument of type X and
Returns a function of type
Y-->Z
The following method is to sum all integers, to sum the squares of all integers and to sum the powers 2^n of all integers n between two given numbers a and b.
// Normal definitions
sum_ints = lambda do |a,b| s = 0 ; a.upto(b){|n| s += n } ; s end sum_of_squares = lambda do |a,b| s = 0 ; a.upto(b){|n| s += n**2 } ;s end sum_of_powers_of_2 = lambda do |a,b| s = 0 ; a.upto(b){|n| s += 2**n } ; s end puts sum_ints.(1,5) #=> 15 puts sum_of_squares.(1,5) #=> 55 puts sum_of_powers_of_2.(1,5) #=> 62
// After factoring out the common pattern by defining a method sum
# Some refactoring to make some abstraction # Passing the sum mechanism itself sum = lambda do |f,a,b| s = 0 ; a.upto(b){|n| s += f.(n) } ; s end puts sum.(lambda{|x| x},1,5) #=> 15 puts sum.(lambda{|x| x**2},1,5) #=> 55 puts sum.(lambda{|x| 2**x},1,5) #=> 62
// Passing the first param to the sum method to specify what type of sum it is
# Refactoring using currying # generate the currying currying = sum.curry Generate the partial functions sum_ints = currying.(lambda{|x| x}) sum_of_squares = currying.(lambda{|x| x**2}) sum_of_powers_of_2 = currying.(lambda{|x| 2**x}) puts sum_ints.(1,5) #=> 15 puts sum_of_squares.(1,5) #=> 55 puts sum_of_powers_of_2.(1,5) #=> 62
Object-Oriented Programming in Ruby
Ruby is the ideal Object Oriented Programming Language, which has four essential properties:
- Data Encapsulation
- Data Abstraction
- Polymorphism
- Inheritance
An object-oriented program consists of classes and objects. An object consists of state and related behavior, where its state is contained within fields and allows access to its behavior through use of methods. These methods can alter an object's state and serve as the facilitator for communication between objects. Classes are defined as the building blocks from which objects are created and will be explained further as we progress through the four properties through the subsequent sections.
Classes
Attributes
Usually methods are defined to give access and power to change the state of an object. If the objects created have a private state, it means no other object can access its instance variables. In other words, object itself is responsible for maintaining its own consistency, however it’s not of much use since you can’t do anything with it. One wants to create methods so that outside world can interact with it. These external visible aspects of an object are called its attributes.
Ruby provides some convenient method to define accessor methods: attr_accessor, attr_writer and attr_reader. Attributes are just a shortcut. If you use attr_accessor to create an attribute, Ruby just declares an instance variable and creates getter and setter methods.
class Thing attr_accessor :my_property attr_reader :my_readable_property attr_writer :my_writable_property def do_stuff # does stuff end end
Writable Attributes
Sometimes you need to be able to set an attribute from outside the object. In Ruby, the attributes of an object can be accessed as if they were any other variable.
class Song def duration=(newDuration) @duration = newDuration end end aSong = Song.new("Bicylops", "Fleck", 260) aSong.duration » 260 aSong.duration = 257 # set attribute with updated value aSong.duration » 257
Ruby also provides a shortcut for creating these simple attribute-setting methods.
class Song attr_writer :duration end aSong = Song.new("Bicylops", "Fleck", 260) aSong.duration = 257
Virtual Attributes
Attribute-accessing methods don’t just have to be simple wrappers around an object's instance variables. In the following example, attribute methods have been used to create a virtual instance variable. To the outside world, durationInMinutes seems to be an attribute like any other but internally; there is no corresponding instance variable.
class Song def durationInMinutes @duration/60.0 # force floating point end def durationInMinutes=(value) @duration = (value*60).to_i end end aSong = Song.new("Bicylops", "Fleck", 260) aSong.durationInMinutes » 4.333333333 aSong.durationInMinutes = 4.2 aSong.duration » 252
Bertrand Meyer calls this as Uniform Access Principle in book Object-Oriented Software Construction. This way the implementation of the class is hidden from the world and is a big advantage.
Inheritance
Access Control
Allowing much access into class has a risk of increased coupling in the application. Users in this case tend to depend on the class's implementation, rather than on its logical interface. Since the only way to change the state of an object is through calling its methods. Hence, Ruby gives us three levels of protection.
• Public methods can be called by anyone and there is no access control. Methods are public by default (except for initialize, which is always private).
• Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
• Private methods cannot be called with an explicit receiver. Since you cannot specify an object when using them, private methods can be called only in the defining class and by direct descendants within that same object.
If a method is protected, it may be called by any instance of the class or its subclasses. If a method is private, it may be called only within the context of the calling object. One can never access another objects private methods directly, even if the object is of the same class as the caller.
Ruby differs from other OO languages in terms of access control i.e. it is determined dynamically, as the program runs, not statically. One will get an access violation only when the code attempts to execute the restricted method.
Specifying Access Control
Access levels are specified to methods within class or module definitions using one or more of these three functions public, protected, and private. Each function can be used in two different ways.
If no arguments are passed, the three functions set the default access control of subsequently defined methods. http://rubylearning.com/satishtalim/ruby_access_control.html
class ClassAccess def m1 # this method is public end protected def m2 # this method is protected end private def m3 # this method is private end end ca = ClassAccess.new ca.m1 #ca.m2 #ca.m3
Removing the comments from the last two statements in the above program, will give an access violation runtime error. Alternatively, one can set access levels of named methods by listing them as arguments to the access control functions.
class ClassAccess def m1 # this method is public end public :m1 protected :m2, :m3 private :m4, :m5 end
A class's initialize method is automatically declared to be private.
Protected access is used when objects need to access the internal state of other objects of the same class.
Abstract Methods
Duck Typing (Unbounded Polymorphism)
References
- (1)http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them
- (2)http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby
- (3)http://en.wikipedia.org/wiki/Closure_(computer_science)
- (4)http://en.wikipedia.org/wiki/Continuation-passing_style
- (5)Flanagan, D and Matsumoto, Y, (2008). The Ruby Programming Language, O’Reilly Media, Inc.,
- (6)Fitzgerald Michael, (2007). Learning Ruby, O’Reilly Media, Inc., (example)
- (7)http://blog.mostof.it/why-ruby-part-two-blocks-and-closures/