4.18.1.1. Jednoduchý příklad

def level3(cont)
    cont.call("RETURN THIS")
end

def level2(cont)
    level3(cont)
    return "NEVER RETURNED"
end

def top_level_function
    callcc { |cc|
        level2(cc)
    }
end

answer = top_level_function
puts answer

# $Id: callcc1.ses,v 1.1 2003/11/30 12:32:45 radek Exp $
def level3(cont)
    cont.call("RETURN THIS")
end
nil
def level2(cont)
    level3(cont)
    return "NEVER RETURNED"
end
nil
def top_level_function
    callcc { |cc|
        level2(cc)
    }
end
nil
answer = top_level_function
"RETURN THIS"
puts answer
RETURN THIS
nil
# Setup the call with the top level continuations.  Notice that we
# create two continuations in this function.  The outer-most one
# (+ret+) is the normal return.  The inner continuation (+failed+)
# is designed to indicate failure by returning a -1 from the top
# level function

def chop_with_cc(target, list)
    callcc { |ret|
        callcc { |failed|
        sub_chop_with_cc(target, list, ret, failed)
        }
        -1
    }
end

# Recursive helper function with continuations explicitly passed in.

def sub_chop_with_cc(target, list, found, not_found)
    if list.size <= 1
        (list[0] == target) ? found.call(0) : not_found.call
    else
        mid = list.size/2
        if list[mid] > target
            sub_chop_with_cc(
                target,
                list[0...mid],
                found,
                not_found)
        else
            found.call(
                mid + callcc { |cc|
                    sub_chop_with_cc(
                        target,
                        list[mid..-1],
                        cc,
                        not_found)
                }
            )
        end
    end
end

class TestChopContinuations < Test::Unit::TestCase
    alias chop chop_with_cc
    include ChopTests
end
Licence Creative Commons
Tento dokument Ruby, jehož autorem je Radek Hnilica, podléhá licenci Creative Commons Uveďte autora-Nevyužívejte dílo komerčně-Zachovejte licenci 3.0 Česká republika .