Last active
March 12, 2017 04:46
-
-
Save mizukmb/b6fe751b9ef1321d1a7662ef0f5e8f2f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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