CSC/ECE 517 Fall 2011/ch3 4b js: Difference between revisions
Line 62: | Line 62: | ||
One difference between the proc kernel method and the lambda kernel method is that the lambda kernel method re | 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: | \\esults in an object that checks the number of its arguments, while a plain Proc.new does not: | ||
Another difference between <b>procs</b> and <b>lambdas</b> is their handling of control flow keywords, such as <b>break</b> and <b>return</b>. Consider the examples below [http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them | Another difference between <b>procs</b> and <b>lambdas</b> is their handling of control flow keywords, such as <b>break</b> and <b>return</b>. Consider the examples below [http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them]. For instance, the first example below shows the difference in behavior using the <b>return</b> keyword. With the proc method, the <b>return</b> not only returns from the proc method, but also the enclosing method, which is shown when the last <b>puts</b> is not called. | ||
<pre> | <pre> | ||
def my_method | def my_method |
Revision as of 15:51, 19 October 2011
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.[1] 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 [2]. 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) [3]
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
To learn more about classes, let us first define a basic Person class.
class Person end
The keyword class is used to define a class type with the class name in camel case, and the keyword end denotes the end of the code block. The Person class defined above explicitly inherits from Object. As we stated before, a class usually has state and behavior, so we will add instance variables, fname and lname , as well as, the necessary accessor methods, getters and setters and a class variable count to keep track of the number of instances of the class created.
class Person @@count = 0 attr_accessor :fname, :lname. def initialize(fname,lname) @fname = fname @lname = lname @@count += 1 end def self.info puts "Number of instances = #{@@count}" end def to_s "Name: #{@fname} #{@lname}" end end
The attr_accessor method dynamically defines the read and write methods for the two instance variables. To instantiate an object of the new class, we use <varname> = <classname>.new(arg1,arg2), which automatically calls the initialize method of the class and passes the arguments to the initialize method. Using our Person class defined above, we can instantiate objects as follows:
pers1 = Person.new("John","Smith") pers2 = Person.new("Tammy","Lee")
Instance Methods
Ruby methods are defined using the keyword def , where the signature is the method name. The to_s method returns a String representation of the object, so for the Person , it returns a string concatenation of the first and last name. Since the to_s method in the Person class is already defined in Object, and we have redefined it in our Person class, Ruby will use the last implementation of the method. Since Ruby returns the value of the last expression of a method as the return value, we can in fact invoke the to_s method in two ways:
#Implicit call to_s puts pers1 #Explicit call to_s str_name = pers1.to_s puts str_name
Class Methods
In Ruby, class methods actually belong to the class and not the instantiation of an object, such as above. In our Person class above, the method self.info is actually a class method, which prints the number of instances of the Person class. A class method is defined by prefixing the method name with the keyword self . When inside an instance method, self is the receiver object, whereas, outside of an instance method, but within a class definition, self, in fact, refers to the class. To invoke a class method, you must call the class method by prefixing it with the class name, where it will resolve to the class.
# Print number of instances. puts Person.info
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 [4]
Ruby provides convenient methods to define accessor methods: attr_accessor, attr_writer and attr_reader. Attributes are just a shortcut i.e. 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.
Attributes, Instance Variables, and Methods
An attribute can act as a method. It can return the value of an instance variable or result of a calculation and sometimes these methods with equals signs at the end of their names are used to update the state of an object [5]
To differentiate an attribute from the method, Dave Thomas, author of the book, Programming ruby, The pragmatic programmers guide, quotes “When you design a class, you decide what internal state it has and also decide how that state is to appear on the outside (to users of your class). The internal state is held in instance variables. The external state is exposed through methods we’re calling attributes. And the other actions your class can perform are just regular methods. It really isn’t a crucially important distinction, but by calling the external state of an object its attributes, you’re helping clue people in to how they should view the class you’ve written.”
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 [6]
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.
Public, Protected and Private Visibility
Summing it up [7]
Public Visibility
- The default access level is “Public”. Public methods are accessible from anywhere (within the class, outside the class, same instance, other instances of same class and sub-classes).
Protected Visibility
- Protected methods are visible to all the instances of the same class as well as sub-classes.
- Protected methods are also accessible from sub-classes. In short, Access control in Ruby neither applies to nor impacts the object hierarchy.
- While accessing protected methods, you can specify the receiver; receiver can by explicit or implicit.
- “Protected” in Ruby is not quite common in other programming languages.
- Private and Protected methods are not directly accessible outside the class.
Private Visibility
- Private methods are private to the instance (and not to the class).
- Private methods are accessible from sub-classes.
- While accessing private methods, one cannot specify the receiver (even if its “self”), receiver is always implicit, never explicit.
- “Private” in Ruby is what “Protected” is in many other languages.
- In Ruby, no method is perfectly private or hidden.
Abstract Methods
Duck Typing (Unbounded Polymorphism)
Relying less on the type (or class) of an object and more on its capabilities is called duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck.
duck << "quack"
In the above example, duck can be a String, a File, or an Array (which is very useful when writing unit tests) [8]
Duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. In duck typing, one is concerned with just those aspects of an object that are used, rather than with the type of the object itself. There is no need for testing the type of arguments in method and function bodies [9]
class Duck def quack puts "Quaaaaaack!" end def feathers puts "The duck has white and gray feathers." end end class Person def quack puts "The person imitates a duck." end def feathers puts "The person takes a feather from the ground and shows it." end end def in_the_forest duck duck.quack duck.feathers end def game donald = Duck.new john = Person.new in_the_forest donald in_the_forest john end game
Output of the above program:
Quaaaaaack! The duck has white and gray feathers. The person imitates a duck. The person takes a feather from the ground and shows it.
In a non-duck-typed language, one can create a function that takes an object of type Duck/Person and calls that object's walk and feathers methods. In a duck-typed language as shown above, the equivalent function would take an object of any type and call that object's walk and feathers methods. If the object does not have the methods that are called then the function signals a run-time error.
References
- http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them
- http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby
- http://en.wikipedia.org/wiki/Closure_(computer_science)
- http://en.wikipedia.org/wiki/Continuation-passing_style
- Flanagan, D and Matsumoto, Y, (2008). The Ruby Programming Language, O’Reilly Media, Inc.,
- Fitzgerald Michael, (2007). Learning Ruby, O’Reilly Media, Inc., (example)
- http://blog.mostof.it/why-ruby-part-two-blocks-and-closures/
- http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/