Robert W. Hasker, 2011-2016 Blocked Ruby.

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

Types in Ruby and other languages….  Classes and objects (vs prototypes)  Instance variables/encapsulation  Object creation  Object equality/comparison.
Michael Donovan, River Campus Libraries – 12/03 DocuShare Overview and Training.
Exceptions COMPSCI 105 S Principles of Computer Science.
1 Dr Alexiei Dingli Web Science Stream Advanced ROR.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
Murach’s ASP.NET 4.0/VB, C1© 2006, Mike Murach & Associates, Inc.Slide 1.
Clojure 4 Sequences 20-Oct-15. Clojure errors (NO_SOURCE_FILE:12) Useless--just means you’re running from the REPL shell java.lang.Exception: EOF while.
Robert W. Hasker, Blocked  Previous uses of blocks  words.each { |w| puts “word: #{w}” }  words.find { |x| x.size > 2 }  Voter.where {
Learning Ruby - 10 Exploiting Classes. Ruby's Class Library Array - an ordered collection of objects Bignum - really big integer values Binding - remembering.
1 Innovative Solutions For Mission Critical Systems Using EMF Annotations to Drive Program Behavior February 19, 2014.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Georgia Institute of Technology Creating Classes part 4 Barb Ericson Georgia Institute of Technology May 2006.
Multithreading vs. Event Driven in Code Development of High Performance Servers.
Robert W. Hasker,  Previous uses of blocks  words.each { |w| puts “word: #{w}” }  words.find { |x| x.size > 2 }  words.select { |x| x.size.
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
Lesson 9: SOFTWARE ICT Fundamentals 2nd Semester SY
Overview Logistics Last lecture Today HW5 due today
ASP.NET Forms.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2017.
Hashing Jeff Chastine.
types in Ruby and other languages…
16. Controlling Loops CSC-3004 Introduction to Software Development
Self Healing and Dynamic Construction Framework:
Naming and Saving Files
© 2016, Mike Murach & Associates, Inc.
Matlab Training Session 4: Control, Flow and Functions
QlikView Licensing.
School of Computer Science and Engineering
The Selection Structure
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Winter 2013.
Classes, Objects, And Variables
White-Box Testing.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Zach Tatlock Winter 2018.
Microsoft Visual Basic 2005 BASICS
Hash table another data structure for implementing a map or a set
Introduction to javadoc
What is Cookie? Cookie is small information stored in text file on user’s hard drive by web server. This information is later used by web browser to retrieve.
Control Structures (Structured Programming) for controlling the procedural aspects of programming CS1110 – Kaminski.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2013.
16. Controlling Loops CSC-3004 Introduction to Software Development
Ruby Testing 2, 11/9/2004.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2016.
What to do when you don’t know anything know nothing
CH 9.2 : Hash Tables Acknowledgement: These slides are adapted from slides provided with Data Structures and Algorithms in C++, Goodrich, Tamassia and.
Chapter 15 Introduction to Rails.
Singleton Pattern Pattern Name: Singleton Pattern Context
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Autumn 2017.
More Looping Structures
Creating Accessible Electronic Documents
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Autumn 2018.
Barb Ericson Georgia Institute of Technology Oct 2005
CH 9.2 : Hash Tables Acknowledgement: These slides are adapted from slides provided with Data Structures and Algorithms in C++, Goodrich, Tamassia and.
6.001 SICP Streams – the lazy way
Introduction to javadoc
Programming Languages
Ruby Containers, Iterators, and Blocks
JavaScript CS 4640 Programming Languages for Web Applications
Tutorial 10: Programming with javascript
Sequences Tuesday, 30 April 2019.
Control Structures (Structured Programming) for controlling the procedural aspects of programming CS1110 – Kaminski.
When to use Context Source in workflow
More Looping Structures
U3L8 Creating Functions with Parameters
Versioning in Adaptive Hypermedia
Code Blocks, Closures, and Continuations
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2019.
Presentation transcript:

Robert W. Hasker, 2011-2016 Blocked Ruby

Blocked Previous uses of blocks Another use: infinite computations 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) The .lazy converts it to a “lazy list”

Blocked Previous uses of blocks Another use: infinite computations 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) The .lazy converts it to a “lazy list” Lazy list

Uses of infinity Prime numbers: require ‘prime’ Prime.first(10) 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 initialize(&block) @block = block @delayed = true end def force @value = @block.call if @delayed @delayed = false @value

How does this work? In general: Processing list: 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. Def of fibonacci from http://stackoverflow.com/questions/6418524/fibonacci-one-liner

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 initialize(logger) @logger = logger end def do_something @logger.post ‘Starting load’ doc = Document.load ‘masterwork.txt’ @logger.post ‘Completed load’ … @logger.post ‘Starting save’ doc.save @logger.post ‘Completed save’

And rescues… def do_something begin @logger.post ‘Starting load’ doc = Document.load ‘masterwork.txt’ @logger.post ‘Completed load’ rescue @logger.post ‘Load failed’; raise end … @logger.post ‘Starting save’ doc.save @logger.post ‘Completed save’ @logger.post ‘Save failed’; raise A lot of code mixed together!

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

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

Blocks and initialization Basic concept behind lazy lists: delayed initialization Consider: class ArchivalDocument attr_reader :title, :author def initialize(title, author, path) @title = title @author = author @path = path end def content @content = @content || File.read(path) Assumption: don’t usually need content for archived object

Blocks and initialization Basic concept behind lazy lists: delayed initialization Consider: class ArchivalDocument attr_reader :title, :author def initialize(title, author, path) @title = title @author = author @path = path end def content @content = @content || File.read(path) Assumption: don’t usually need content for archived object Limitation: only works for files

Blocks to the rescue: class ArchivalDocument attr_reader :title, :author def initialize(title, author, &reader_block) @title = title @author = author @reader = reader_block end def content if @reader @content = @reader.call @reader = nil @content

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

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