Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)
Paste
Pasted as Ruby by disa ( 17 years ago )
class NilClass
def filter(&pred)
nil
end
def take(n)
nil
end
def map(&fn)
nil
end
end
class Stream
def initialize(head, &tail)
@head = head
@runned = false
@res = nil
@tail = lambda{ @runned ? @res : (@runned = true; @res = tail.call) }
end
def head
@head
end
def tail
@tail.call
end
def take(n)
if n < 1
nil
else
Stream.new(self.head){ (n == 1) ? nil : self.tail.take(n - 1) }
end
end
def filter(&pred)
if pred.call(self.head)
Stream.new(self.head){ self.tail.filter(&pred) }
else
self.tail.filter(&pred)
end
end
def map(&fn)
Stream.new(fn.call(self.head)){ self.tail.map(&fn) }
end
def to_a
[self.head] + self.tail.to_a
end
def merge(other)
Stream.new(self.head){ Stream.new(other.head){ self.tail.merge(other.tail) } }
end
def +(other)
Stream.new(self.head + other.head){ self.tail + other.tail }
end
def [](index)
if index < 1
self.head
else
self.tail[index - 1]
end
end
end
def cons(a, &b)
Stream.new(a, &b)
end
def car(xs)
xs.head
end
def cdr(xs)
xs.tail
end
def amounts
cons(3){ cons(5){ cons(2){ cons(7){ } } } }
end
def withdraws(balance, amounts)
cons(balance){ amounts.tail.nil? ? nil : withdraws(balance - car(amounts), cdr(amounts)) }
end
withdraws(20, amounts).to_a
Revise this Paste