Created
December 12, 2012 06:43
-
-
Save cstrahan/4265576 to your computer and use it in GitHub Desktop.
Ruby quizes!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# implement the functions `amb` and `assert`. | |
# `amb` must choose a value from a given set, | |
# such that all assertions pass. | |
# as an example, the following program: | |
a = amb [1,2,3,4,5,6,7] | |
b = amb [1,2,3,4,5,6,7] | |
c = amb [1,2,3,4,5,6,7] | |
# a, b and c must define a legal right triangle: | |
assert c**2 == a**2 + b**2 | |
# and side b is smaller than side a | |
assert b < a | |
# print the results: | |
puts [a,b,c].join " " | |
# RESULT: 4 3 5 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'continuation' | |
def fail_stack | |
(@fail_stack ||= []) | |
end | |
def failure | |
throw "back tracking stack exhausted!" if fail_stack.empty? | |
cc = fail_stack.shift | |
cc.call cc | |
end | |
def amb choices | |
cc = callcc {|cc| cc} | |
failure if choices.empty? | |
choice = choices.shift | |
fail_stack.unshift cc | |
choice | |
end | |
def assert condition | |
failure unless condition | |
true | |
end | |
# let's test it out | |
a = amb [1,2,3,4,5,6,7] | |
b = amb [1,2,3,4,5,6,7] | |
c = amb [1,2,3,4,5,6,7] | |
assert c**2 == a**2 + b**2 | |
assert b < a | |
puts [a,b,c].join " " |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment