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

Defined Under Namespace

Modules: ClassMethods, Operator Classes: ExhaustedError

Constant Summary collapse

MAJOR =
0
MINOR =
0
PATCH =
5
VERSION =
[MAJOR, MINOR, PATCH].join('.')

Class Method Summary collapse

Instance Method Summary collapse

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.

Parameters:

  • cond

Yields:


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_ambArray<Proc, Continuation>

Memoize and return the alternatives associated continuations.

Returns:

  • (Array<Proc, Continuation>)

84
85
86
# File 'lib/amb/amb.rb', line 84

def back_amb
  @__back_amb ||= [Proc.new { fail ExhaustedError, "amb tree exhausted" }]
end

#branches_countObject


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.

Parameters:

  • choices

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

#failureObject

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.

Parameters:

  • failure_message (#to_s)

140
141
142
# File 'lib/amb/amb.rb', line 140

def report(failure_message)
  puts failure_message
end