kof2008 itll
DESCRIPTION
“Introduction to Lazy lists”How to use and construct lazy lists on Programming Langage Ruby.TRANSCRIPT
Introduction to Lazy Lists2008 UJIHISA, Tatsuhiro
UJIHISA Tatsuhiro• Osaka University
• Ruby, Vim, Haskell and Math
• http://ujihisa.nowa.jp
• http://twitter.com/ujm
• To the US!
Targets
• ★★☆☆☆• Array, Enumerable, IO (File)
Haskell
Lazy lists
• RubyやHaskellを用いて遅延リスト (Lazy list) の概念とその有用性の議論を展開する。説明にはLive codingが含まれる。もしも時間が余れば、全てのプログラマにとって有用である伝統的ツールVimについて簡単な紹介を行う。
Lazy Lists• Lazy lists (or streams)
• List (= Array in Ruby)
• Only needed parts are calculated.
• Haskell supports lazy lists by default.
• Ruby can support it.
List (=Array) in Ruby• Array class
• [0, 1, 2, 3], Array.new(4) {|i| i }
• a #=> [0, 1, 2, 3]a.map {|i| i * 2 } #=> [0, 2, 4, 6]
List• Data structure
• Insert, Delete, Access sequentially
c.f. Array• Data structure
• Insert, Delete, Access randomly, Size
(List again)• Data structure
• Insert, Delete, Access sequentially
Lazy List• Data structure
• Insert, Delete, Access sequentially
Types of lazy lists
• Boundless length lists (長さが無限)
• Undefined length lists (長さが未定義)
• Defined length lists (長さが定義済み)
How to constructlazy lists?
1 class LazyList 2 def initialize(&b) 3 @b = b 4 @i = -1 5 end 6 7 def succ 8 @b[@i+=1] 9 end 10 end
l = LazyList.new {¦i¦ i * 2 } 10.times do p l.succend
def each loop { yield succ }end
l = LazyList.new {¦i¦ i * 2 } l.each do ¦i¦ p i break if i > 10end
Notations• array = 1000+ length array
heavy = lambda { heavy procedure }
• array.take(2).map(&heavy)
• array.map(&heavy).take(2)
File.open(__FILE__) do ¦io¦ a = nil while a = io.gets do p a endend
File.open(__FILE__) do ¦io¦ io.each do ¦a¦ p a endend
File.open(__FILE__) do ¦io¦ io.each do ¦a¦ if a != "\n" p a end endend
File.open(__FILE__) do ¦io¦ io.select {¦a¦ a != "\n" }.each {¦a¦ p a }end
File.open(__FILE__) do ¦io¦ io.each do ¦a¦ if a != "\n" p a end endend
File.open(__FILE__) do ¦io¦ io.select {¦a¦ a != "\n" }.each {¦a¦ p a }end
File.open(__FILE__) do ¦io¦ io. select {¦a¦ a != "\n" }. each {¦a¦ p a }end
Common case• truncation (break)
• filtering (if, unless; select, reject)
• mapping (=, map)
• processing (???, each)folding (<<, inject)
list.each {¦a¦ next if ... b = ... ...}
list. select { ... }. map { ... }. each { ... }
result = 0list.each {¦a¦ next if ... b = ... result += b}
result = list. select { ... }. map { ... }. inject(0) { ... }
$ sudo gem install lazylist
sq = list { x * x }.where :x => 1..Infinity
# Haskell!# sq = [ x * x ¦ x <- [1..] ]