Module: Amb
- Extended by:
- Amb, selfself::ClassMethods
- Included in:
- Amb
- Defined in:
- lib/amb/amb.rb,
lib/amb/version.rb,
lib/amb/amb_operator.rb
Overview
By Eric Kidd. See www.randomhacks.net/articles/2005/10/11/amb-operator.
Defined Under Namespace
Modules: ClassMethods, Operator Classes: ExhaustedError
Constant Summary collapse
Class Method Summary collapse
Instance Method Summary collapse
-
#assert(*args) { ... } ⇒ Object
Assert the given condition is true.
-
#back_amb ⇒ Array<Proc, Continuation>
Memoize and return the alternatives associated continuations.
- #branches_count ⇒ Object
-
#choose(*choices) ⇒ Object
(also: #choices, #alternatives)
Make a choice amoung a set of discrete values.
-
#failure ⇒ Object
Unconditional failure of a constraint, causing the last choice to be retried.
-
#report(failure_message) ⇒ Object
Report the given failure message.
Class Method Details
.included(base) ⇒ Object
76 77 78 |
# File 'lib/amb/amb.rb', line 76 def self.included(base) base.extend(ClassMethods) end |
Instance Method Details
#assert(*args) { ... } ⇒ Object
Assert the given condition is true. If the condition is false, cause a failure and retry the last choice. One may specify the condition either as an argument or as a block. If a block is provided, it will be passed the arguments, whereas without a block, the first argument will be used as the condition.
127 128 129 130 |
# File 'lib/amb/amb.rb', line 127 def assert(*args) cond = block_given? ? yield(*args) : args.first failure unless cond end |
#back_amb ⇒ Array<Proc, Continuation>
Memoize and return the alternatives associated continuations.
84 85 86 |
# File 'lib/amb/amb.rb', line 84 def back_amb @__back_amb ||= [Proc.new { fail ExhaustedError, "amb tree exhausted" }] end |
#branches_count ⇒ Object
144 145 146 |
# File 'lib/amb/amb.rb', line 144 def branches_count @__num_of_tries end |
#choose(*choices) ⇒ Object Also known as: choices, alternatives
Make a choice amoung a set of discrete values.
92 93 94 95 96 97 98 99 100 |
# File 'lib/amb/amb.rb', line 92 def choose(*choices) choices.each do |choice| callcc do |fk| back_amb << fk return choice end end failure end |
#failure ⇒ Object
Unconditional failure of a constraint, causing the last choice to be retried. This is equivalent to saying ‘assert(false)`.
Use to force a search for another solution (see examples).
110 111 112 113 114 115 116 |
# File 'lib/amb/amb.rb', line 110 def failure if $DEBUG @__num_of_tries ||= 1 @__num_of_tries += 1 end back_amb.pop.call end |
#report(failure_message) ⇒ Object
Report the given failure message. This is called by solve in the event that no solutions are found, and by solve_all when no more solutions are to be found. Report will simply display the message to standard output, but you may override this method in a derived class if you need different behavior.
140 141 142 |
# File 'lib/amb/amb.rb', line 140 def report() puts end |