Add NFA#to_s

This commit is contained in:
Josh Holtrop 2021-05-21 14:24:16 -04:00
parent 43f5caf449
commit f64f3683c6

View File

@ -27,6 +27,40 @@ module Imbecile
@end_state = State.new @end_state = State.new
end end
def to_s
rv = ""
states = {start_state => 0}
to_visit = [start_state]
state_id = lambda do |state|
unless states.include?(state)
states[state] = states.values.max + 1
to_visit << state
end
states[state]
end
visit = lambda do |state|
accepts_s = state.accepts ? " *" : ""
rv += "#{state_id[state]}#{accepts_s}:\n"
state.transitions.each do |range, dest_state|
if range.nil?
range_s = "nil"
else
range_s = range.first.chr
if range.size > 1
range_s += "-" + range.last.chr
end
end
accepts_s = dest_state.accepts ? " *" : ""
rv += " #{range_s} => #{state_id[dest_state]}#{accepts_s}\n"
end
end
while to_visit.size > 0
visit[to_visit[0]]
to_visit.slice!(0)
end
rv
end
class << self class << self
def empty def empty