teaching machines

CS 330 Lecture 36 – Lazy Evaluation

May 4, 2015 by . Filed under cs330, lectures, spring 2015.

Agenda

Intentions

Code

Until.scala

object Main {
  def main(args: Array[String]) {
    // while (repeat) { 
      // body 
    // } 

    // until (!repeat) { 
      // body 
    // } 

    // until(i == 12, { 
      // println(i) 
      // i += 1 
    // }) 

    var i = 0
    until (i == 12) {
      println(i)
      i += 1
    }
  }

  def until(condition: => Boolean)(body: => Unit) {
    while (!condition) {
      body
    }
  }
}

Lazy.rb

#!/usr/bin/env ruby

require 'open-uri'

class Lazy
  def initialize &thunk
    @thunk = thunk
    @cache = nil
  end

  def get
    if not @cache
      @cache = @thunk.call
    end
    @cache
  end
end

lazy = Lazy.new do
  puts "I'm a thunky chicken."
  open('http://www.twodee.org/tests/slowimage/slowimage.php').read
end

# puts lazy.get.length 
# puts lazy.get.length 
# puts lazy.get.length 
# puts lazy.get.length 
# puts lazy.get.length 
# puts lazy.get.length 

class ForeverRange
  def initialize first
    @first = first
    @rest = Lazy.new {ForeverRange.new first + 1}
  end

  def first
    @first
  end

  def rest
    @rest.get
  end
end

i = ForeverRange.new 2
100000000000.times do
  puts i.first
  i = i.rest
end

Haiku

on saying yes
My Now box is full
Later is overflowing
Never sits empty