Skip to content

Instantly share code, notes, and snippets.

@takahisa
Created December 8, 2011 08:39
Show Gist options
  • Save takahisa/1446471 to your computer and use it in GitHub Desktop.
Save takahisa/1446471 to your computer and use it in GitHub Desktop.
class Parser
rule
target : unit
| { result = 0 }
unit : stat
| unit stat
stat : expr SEMICOLON
expr_list : expr
| expr_list expr
expr : bind
| lambda
| applicative
term : IDENTIFIER { result = Reference.new(val[0]) }
| INTEGER { result = Constant.new(val[0]) }
| STRING { result = Constant.new(val[0]) }
| LETTER { result = Constant.new(val[0]) }
| LPAREN RPAREN { result = Constant.new([]) }
| LPAREN expr_list RPAREN { result = val[1] }
bind : LET IDENTIFIER COLON expr
| LET IDENTIFIER COLON expr ARROW expr
lambda : LAMBDA IDENTIFIER ARROW expr
applicative : term
| applicative term { result = Applicative.new(val[0],val[1]) }
end
----header
class Contant
def initialize(value)
@value = value
end
def evaluate(scope)
@value
end
def to_s()
"\"#{@value}\""
end
end
class Reference
def initialize(id)
@id = id
end
def evaluate(scope)
scope[@id]
end
def to_s()
"#{@id}"
end
end
class Cell
def initialize(car,cdr)
@car = car
@cdr = cdr
end
def evaluate(scope)
[@car,@cdr]
end
def to_s()
"(#{@car},#{@cdr})"
end
end
class Lambda
def initialize(id,expr)
@id = id
@expr = expr
end
def evaluate(scope)
lambda { |arg|
scope[@id] = arg
@expr.evaluate(@id)
}
end
def to_s()
"(#{@id} -> #{@expr})"
end
end
class Applicative
def initialize(expr,parameter)
@expr = expr
@parameter = parameter
end
def evaluate(scope)
end
def to_s()
"(#{@expr} #{@parameter})"
end
end
class Scope
def initialize(parent= nil,table = init_table())
@parent = parent
@table = table
end
def []=(id,value)
@table[id] = value
end
def [](id)
result = self[id]
return result if result
if self.parent
self.parent[id]
else
nil
end
end
def local()
Scope.new(self,{})
end
def parent()
@parent
end
def init_table()
table = {}
table
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment