>>>>> "Dave" == Dave Thomas <Dave / thomases.com> writes:

    Dave> If you're into writing control structures, you could also
    Dave> have a look at Ruby's continuations. It has the equivalent
    Dave> of Scheme's callcc mechanism.

    Dave> http://dev.rubycentral.com/ref/ref_c_continuation.html

    Dave> If you come up with anything neat, please post it: the FAQ
    Dave> needs a good continuation example.

I don't know if this counts as cool ... but here is an example using
continuations.

# ====================================================================
# Continuation Examples
# Author: Jim Weirich (jweirich / one.net)
# ====================================================================

# --------------------------------------------------------------------
# Simple Producer/Consumer
# --------------------------------------------------------------------
# Connect a simple counting task and a printing task together using
# continuations.
#
# Usage:  count(limit)

def count_task (count, consumer)
  (1..count).each do
    |i|
    callcc {|cc| consumer.call cc, i }
  end
  nil
end

def print_task ()
  producer, i = callcc { |cc| return cc }
  print "#{i} "
  callcc { |cc| producer.call }
end

def count (limit)
  count_task (limit, print_task())
  print "\n"
end


# --------------------------------------------------------------------
# Filtering Out Multiples of a Given Number
# --------------------------------------------------------------------
# Create a filter that is both a consumer and producer.  Insert it
# between the counting task and the printing task.
# 
# Usage:  omit (2, limit)

def filter_task (factor, consumer)
  producer, i = callcc { |cc| return cc }
  if (i%factor) != 0 then
    callcc { |cc| consumer.call cc, i }
  end
  producer.call
end

def omit (factor, limit)
  printer = print_task ()
  filter = filter_task (factor, printer)
  count_task (limit, filter)
  print "\n"
end


# --------------------------------------------------------------------
# Prime Number Generator
# --------------------------------------------------------------------
# Create a prime number generator.  When a new prime number is
# discovered, dynamically add a new multiple filter to the chain of
# producers and consumers.
#
# Usage:  primes (limit)

def prime_task (consumer)
  producer, i = callcc { |cc| return cc }
  if i >= 2 then
    callcc { |cc| consumer.call cc, i }
    consumer = filter_task (i, consumer)
  end
  producer.call
end

def primes (limit)
  printer = print_task ()
  primes = prime_task (printer)
  count_task (limit, primes)
  print "\n"
end

# ====================================================================


-- 
-- Jim Weirich     jweirich / one.net    http://w3.one.net/~jweirich
---------------------------------------------------------------------
"Beware of bugs in the above code; I have only proved it correct, 
not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)