At 01:44 AM 8/21/01, you wrote:
>  You can, perhaps, use #catch
>
>    puts (catch(:end) do
>       for i in 0 .. 5
>          for j in 5 .. 8
>             throw :end, "match" if i == j
>          end
>       end
>       "nomatch"
>    end)


I was in a "chess puzzle" mood, so I extended this to let you resume a loop 
if the first match you find isn't to your liking. First, I made the above a 
function, so the caller can do the puts:

def find_match(first_range, next_range)
   catch(:end) do
     for i in first_range
       for j in next_range
         throw(:end,"match: #{i}") if i == j
       end
     end
     "nomatch"
   end
end

 > puts find_match(0..3, 2..5)
match: 2

Now, switch to the equivalent function that uses callcc instead of catch/throw:

def find_match_2(first_range, next_range)
   callcc do | out |         # CHANGE
     for i in first_range
       for j in next_range
         out.call("match: #{i}") if i == j   # CHANGE
       end
     end
     "nomatch"
   end
end

 > puts find_match_2(0..3, 2..5)
match: 2

Now, return two values: the return value and a continuation that you can 
call to resume the loop. That will work like this:

 > val, restart = find_match_3(0..3, 2..5)
 > puts val
match: 2

# Hmm, don't like that match.
 > val, restart = restart.call
 > puts val
match: 3

# Don't like that one either.
 > val, restart = restart.call
 > puts val
nomatch

# Rats.

Here's the code:

def find_match_3(first_range, next_range)
   callcc do | out |
     for i in first_range
       for j in next_range
         if i == j
           return_resumably("match: #{i}", out)   # CHANGE
         end
       end
     end
     "nomatch"
   end
end

# Just like the process switch code in the V6 Unix kernel!
def return_resumably(primary_retval, return_continuation)
   returning_now = true
   resume_continuation = nil
   callcc { | resume_continuation |; }
   if returning_now
     returning_now = false
     return_continuation.call(primary_retval, resume_continuation)
   end
end

I wonder if there's a cleaner way to do this, but I must do some paying 
work now.

--
Brian Marick, marick / testing.com
www.testing.com - Software testing services and resources
www.testingcraft.com - Where software testers exchange techniques
www.visibleworkings.com - Adequate understanding of system internals