Skip to content

Instantly share code, notes, and snippets.

@mizukmb
Last active Mar 12, 2017
Embed
What would you like to do?
module MS
def print(token)
case token
when MAtom
token.token
when Array
"( #{token.map{ |t| print(t) }.join(' ')} )"
else
raise 'Syntax Error!!'
end
end
module_function :print
end
class MAtom
attr_reader :token
def initialize(token)
@token = token
end
end
class MNil
attr_reader :nil
def initialize
@nil = nil
end
end
class MPaer
attr_reader :car, :cdr
def initialize(car, cdr)
@car = car
@cdr = cdr
end
end
class MLexer
def initialize(str)
@chars = str.split('')
@index = 0
@depth = 0
@ret = []
end
def run
if current_token == '('
@depth = 1
next!
while @chars.size > @index
case current_token
when '('
@ret.push( [] )
@depth += 1
next!
when %r([a-zA-Z0-9])
tmp = ""
loop do
tmp += current_token
next!
break unless current_token =~ %r([a-zA-Z0-9])
end
if @depth == 1
@ret.push( MAtom.new(tmp) )
else
@ret[@depth-1].push( MAtom.new(tmp) )
end
when ')'
@depth -= 1
next!
when ' '
next!
else
raise 'Parse Error!!'
end
end
else
raise 'Parse Error!!'
end
raise "Syntax Error!!" if @depth != 0
@ret
end
private
def current_token
@chars[@index]
end
def next!
@index += 1
end
end
a = MLexer.new('( atom ( 2 3 ) )').run
puts MS.print(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment