CS 330 Lecture 36 – Lazy Evaluation
Agenda
- what ?s
- call-by-name
- adding
until
to Scala - call-by-need
Intentions
- I can exploit call-by-name semantics to pass around unevaluated blocks of code, which can be used to implement control abstractions.
- I can exploit call-by-need semantics to implement lazy data structures.
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
My Now box is full
Later is overflowing
Never sits empty