Class: Calyx::Grammar::Production::WeightedChoices
- Inherits:
-
Object
- Object
- Calyx::Grammar::Production::WeightedChoices
- Defined in:
- lib/calyx.rb
Class Method Summary collapse
Instance Method Summary collapse
- #evaluate(registry) ⇒ Object
-
#initialize(collection) ⇒ WeightedChoices
constructor
A new instance of WeightedChoices.
Constructor Details
#initialize(collection) ⇒ WeightedChoices
102 103 104 |
# File 'lib/calyx.rb', line 102 def initialize(collection) @collection = collection end |
Class Method Details
.parse(productions) ⇒ Object
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/calyx.rb', line 84 def self.parse(productions) weights_sum = productions.reduce(0) do |memo, choice| memo += choice.last end raise 'Weights must sum to 1' if weights_sum != 1.0 choices = productions.map do |choice, weight| if choice.is_a?(String) [Concat.parse(choice), weight] elsif choice.is_a?(Symbol) [NonTerminal.new(choice), weight] end end self.new(choices) end |
Instance Method Details
#evaluate(registry) ⇒ Object
106 107 108 109 110 111 112 |
# File 'lib/calyx.rb', line 106 def evaluate(registry) choice = @collection.max_by do |_, weight| rand ** (1.0 / weight) end.first choice.evaluate(registry) end |