Skip to content

Instantly share code, notes, and snippets.

@lp
Created June 4, 2009 21:37
Show Gist options
  • Select an option

  • Save lp/123868 to your computer and use it in GitHub Desktop.

Select an option

Save lp/123868 to your computer and use it in GitHub Desktop.
essai on context free modes
#!/usr/bin/env ruby
# -4 add separate recurse and iterate... iterate not implemented but routed
# -5 add a progressive recurse... sort of
# -6 the progressive recurse is really the same a the recurse, but progressive,
# then the progressive has become an infinite type
# -8 cleaned up... abandonned iterate, infinite and stacked
$total = 0
$nist = 0
$bl1 = 0
$bl2 = 0
class ContextFree
def self.recurse(&block)
cf = ContextFree.new
cf.instance_variable_set(:@type, :recurse)
cf.instance_eval( &block)
cf.instance_eval(
&cf.instance_variable_get(:@rules)[
cf.instance_variable_get(:@startshape)][
rand( cf.instance_variable_get(:@rules)[
cf.instance_variable_get(:@startshape)].size)-1]
) if cf.instance_variable_defined?(:@startshape)
cf
end
def self.progress(&block)
cf = ContextFree.new
cf.instance_variable_set(:@type, :progress)
cf.instance_eval( &block)
t = Thread.new do
cf.instance_eval(
&cf.instance_variable_get(:@rules)[
cf.instance_variable_get(:@startshape)][
rand( cf.instance_variable_get(:@rules)[
cf.instance_variable_get(:@startshape)].size)-1]
)
end
cf.instance_variable_set(:@thread, t)
cf
end
def initialize
@nesting = 5
@rules = Hash.new
end
def done?
@thread.nil? ? true : false
end
def step
if @type == :progress
begin
@thread.run
rescue ThreadError
@thread = nil
end
end
end
def startshape(name)
@startshape = name
end
def nesting(num)
@nesting = num
end
def rule(name,&block)
@rules[name] = Array.new unless @rules.include?(name)
@rules[name] << block
end
def poo(word)
$total += 1
puts "++#{$total} " + word
end
def method_missing(*args)
name = args.shift
run(name)
end
private
def run(name)
trace = caller(0)
@rules[name][rand(@rules[name].size)-1].call unless max_recurse?( trace)
end
def max_recurse?(trace)
selected = trace.select { |i| i =~ /run'$/ }
selected.size - selected.uniq.size < @nesting ? false : true
end
end
cf = ContextFree.progress do
startshape :myrule
nesting 5
rule :nist do
$nist += 1
poo "nist#{$nist}"
myrule
end
rule :nist do
$nist += 1
poo ">>>>>>>>>>>>nist#{$nist}"
nist
end
rule :myrule do
$bl1 +=1
poo 'glass' + $bl1.to_s
myrule
nist
end
rule :myrule do
$bl2 +=1
poo '>>>>>>>>>>>>glass' + $bl2.to_s
nist
myrule
end
end
# when its progressive
until cf.done?
cf.step
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment