Robert W. Hasker, 2011-2016.  Previous uses of blocks  words.each { |w| puts “word: #{w}” }  words.find { |x| x.size > 2 }  words.select { |x| x.size.

Slides:



Advertisements
Similar presentations
Decision Structures - If / Else If / Else. Decisions Often we need to make decisions based on information that we receive. Often we need to make decisions.
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 15 Introduction to Rails.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
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.
Types in Ruby and other languages….  Classes and objects (vs prototypes)  Instance variables/encapsulation  Object creation  Object equality/comparison.
Implementing declarative overlays Boom Thau Loo Tyson Condie Joseph M. Hellerstein Petros Maniatis Timothy Roscoe Ion Stoica.
A Program Transformation For Faster Goal-Directed Search Akash Lal, Shaz Qadeer Microsoft Research.
Evaluation of a Scalable P2P Lookup Protocol for Internet Applications
Introduction to C Programming
Learning Ruby Methods. We’ve seen several so far: puts, gets, chomp, to_s, and even +, -, * and / Usually use dot notation is really just a shortcut.
KISS Programming. What’s so great about computers? They are fast (so they can accomplish much in a short time… spell check a thesis) They don’t make mistakes.
Introduction To Form Builder
Chapter 2: Algorithm Discovery and Design
Fundamentals of Python: From First Programs Through Data Structures
Ruby (on Rails) CSE 190M, Spring 2009 Week 4. Constructors Writing a new class is simple! Example: class Point end But we may want to initialize state.
Python quick start guide
Software Testing Sudipto Ghosh CS 406 Fall 99 November 9, 1999.
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.
Exceptions COMPSCI 105 S Principles of Computer Science.
More Looping Structures
Objectives Understand the basic concepts and definitions relating to testing, like error, fault, failure, test case, test suite, test harness. Explore.
RUP Implementation and Testing
Chapter 19: Adding JavaScript
THE BIG PICTURE. How does JavaScript interact with the browser?
Programmer's view on Computer Architecture by Istvan Haller.
1 Dr Alexiei Dingli Web Science Stream Advanced ROR.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and Elizabeth Drake Chapter 2: Flowcharts.
1 RTOS Design Some of the content of this set of slides is taken from the documentation existing on the FreeRTOS website
Procrastinator: Pacing Mobile Apps’ Usage of the Network mobisys 2014.
Database control Introduction. The Database control is a tool that used by the database administrator to control the database. To enter to Database control.
Robert W. Hasker, Blocked  Previous uses of blocks  words.each { |w| puts “word: #{w}” }  words.find { |x| x.size > 2 }  Voter.where {
1 Innovative Solutions For Mission Critical Systems Using EMF Annotations to Drive Program Behavior February 19, 2014.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Troubleshooting Security Issues Lesson 6. Skills Matrix Technology SkillObjective Domain SkillDomain # Monitoring and Troubleshooting with Event Viewer.
Department of Computer Science Internet Performance Measurements using Firefox Extensions Scot L. DeDeo Professor Craig Wills.
Topic 1 – Introduction Huiqun Yu Information Security Principles & Applications.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
Georgia Institute of Technology Creating Classes part 4 Barb Ericson Georgia Institute of Technology May 2006.
Introduction to Microsoft Excel Macros COE 201- Computer Proficiency.
Introduction to Ruby&Rails Yuri Veremeyenko Monica Verma.
Input Boxes, List Boxes, and Loops Chapter 5. 2 Input Boxes Method for getting user’s attention to obtain input. InputBox() for obtaining input MessageBox()
IST 210: PHP LOGIC IST 210: Organization of Data IST210 1.
IBM Express Runtime Quick Start Workshop © 2007 IBM Corporation Deploying a Solution.
Multithreading vs. Event Driven in Code Development of High Performance Servers.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
CSE 341 Lecture 21 delayed evaluation; thunks; streams slides created by Marty Stepp
Test Title Test Content.
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
types in Ruby and other languages…
Robert W. Hasker, Blocked Ruby.
Matlab Training Session 4: Control, Flow and Functions
The Selection Structure
Classes, Objects, And Variables
White-Box Testing.
Microsoft Visual Basic 2005 BASICS
Hash table another data structure for implementing a map or a set
Important Concepts from Clojure
Control Structures (Structured Programming) for controlling the procedural aspects of programming CS1110 – Kaminski.
Important Concepts from Clojure
Ruby Testing 2, 11/9/2004.
Programming Languages
Ruby Containers, Iterators, and Blocks
Stoke 100 Reads Reading log Name: Class:.
Tutorial 10: Programming with javascript
Control Structures (Structured Programming) for controlling the procedural aspects of programming CS1110 – Kaminski.
Stoke Reads On Reading log Name: Class:.
Code Blocks, Closures, and Continuations
Presentation transcript:

Robert W. Hasker,

 Previous uses of blocks  words.each { |w| puts “word: #{w}” }  words.find { |x| x.size > 2 }  words.select { |x| x.size % 2 == 0 }  Another use: infinite computations  Open irb and type nats = 0..(1.0/0) nats.take(100) nats.step(2).first(10)  Skipping: nats.step(2).lazy.drop(50).first(10) Blocked

 Previous uses of blocks  words.each { |w| puts “word: #{w}” }  words.find { |x| x.size > 2 }  words.select { |x| x.size % 2 == 0 }  Another use: infinite computations  Open irb and type nats = 0..(1.0/0) nats.take(100) nats.step(2).first(10)  Skipping: nats.step(2).lazy.drop(50).first(10) Blocked Lazy list

Uses of infinity  squares = nats.lazy.map { |n| n * n }  Prime numbers:  require ‘prime’  Prime.first(10)  Prime.lazy.drop(1000). select { |x| (x+1)%3 == 0 }.first(5)

How does this work?  Ruby code to delay evaluation: class Promise def = = true end def @delayed = end

How does this work?  In general:  Delay: promise to provide value when requested  Force: call in the promise  Processing list:  force head when required, delay rest  Ruby implementation: blocks  Useful tool when want to delay execution in general

Yet more blockhead actions  Computing Fibonacci numbers: fibonacci = Hash.new{ |h,k| h[k] = k < 2 ? k : h[k-1] + h[k-2] }  From Ruby documentation:  If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block’s responsibility to store the value in the hash if required.

Using blocks creatively  From Eloquent Ruby by Russ Olsen, 2011  How to log events smoothly?  Consider: class WonderApplication def do_something doc = Document.load ‘masterwork.txt’ … doc.save end

Adding logging class WonderApplication def = logger end def ‘Starting load’ doc = Document.load ‘Completed load’ ‘Starting save’ ‘Completed save’ end

And rescues… def do_something ‘Starting load’ doc = Document.load ‘Completed load’ ‘Load failed’; raise end … ‘Starting save’ ‘Completed save’ ‘Save failed’; raise end

Fix: def with_logging(description) “Starting #{description}” “Completed #{description}” “#{description} failed”; raise end def do_something with_logging(‘load’) = Document.load ‘masterwork.txt’ } … with_logging(‘save’) } end

Fix: def with_logging(description) “Starting #{description}” “Completed #{description}” “#{description} failed”; raise end def do_something with_logging(‘load’) = Document.load ‘masterwork.txt’ } … with_logging(‘save’) } end “Execute around”

Blocks and initialization  Basic concept behind lazy lists: delayed initialization  Consider: class ArchivalDocument attr_reader :title, :author def initialize(title, author, = = = path end def || File.read(path) end

Blocks and initialization  Basic concept behind lazy lists: delayed initialization  Consider: class ArchivalDocument attr_reader :title, :author def initialize(title, author, = = = path end def || File.read(path) end

Blocks and initialization  Basic concept behind lazy lists: delayed initialization  Consider: class ArchivalDocument attr_reader :title, :author def initialize(title, author, = = = path end def || File.read(path) end

Blocks to the rescue: class ArchivalDocument attr_reader :title, :author def initialize(title, author, = = = reader_block end def @reader = nil end

Usage simple_file_doc = ArchivalDocument.new(‘Rubies Forever’, ‘Tim’) do File.read(‘c:/books/rubies_forever.txt’) end google_doc = ArchivalDocument.new(‘Sherlock Holmes’, ‘Conan Doyle’) do Net::HTTP.get_response(‘books.google.com’, ‘/books?id=QhPgEq5ZeY8C’).body end boring_doc = ArchivalDocument.new(‘silly’, ‘Rob’) do ‘Ya’ * 100 end

Summary  Infinite ranges, lists  Generating streams  Execute around  Embed computations in a context  Lazy initialization  Application of lazy list concept to initialization  Basic principles:  Delayed execution  Stored behaviors