Skip to content

Instantly share code, notes, and snippets.

@hsk
Last active October 3, 2017 15:14
Show Gist options
  • Save hsk/0652918e757aab3efcf86c54949b1f8e to your computer and use it in GitHub Desktop.
Save hsk/0652918e757aab3efcf86c54949b1f8e to your computer and use it in GitHub Desktop.
class MatchError
attr_accessor :r
def initialize(a)
@r = self
@match = a
end
def >>(a)
self
end
def >=(a)
self
end
def |(a)
p "match or"
@match>>a
end
def m(a,b)
self
end
end
class End
attr_accessor :r
def initialize(a)
@r = a
end
def >>(a)
self
end
def >=(a)
self
end
def |(a)
self
end
def m(a,b)
self
end
end
class Match
attr_accessor :s,:r
def initialize(a)
@init = a
@s = a
end
def |(a)
p "or"
End.new(@r)
end
def >>(a)
a.call(self)
end
def >=(a)
@r=a.call(self)
self
end
def m(a,b)
s=~ a
if $1 == nil then
@s=@init
return MatchError.new(self)
end
@s=$2
singleton_class.class_eval { attr_accessor b }
send("#{b}=", $1)
self
end
end
def int a
->s{s.m(/^([0-9]+)(.*$)/,a)}
end
def op a
->s{s.m(/^([+-])(.*$)/,a)}
end
def op2 a
->s{s.m(/^([*\/])(.*$)/,a)}
end
p ((((Match.new("123/456")>>int(:a)>>op(:o)>>int(:b)>=->s{[s.a,s.o,s.b]}) | int(:a))>>op2(:o)>>int(:b)>=->s{[s.a,s.o,s.b]}).r)
p (((Match.new("123-456")>>int(:a)>>op(:o)>>int(:b))>=->s{[s.a,s.o,s.b]}).r)
p (((Match.new("123-456")>>int(:a)>>op(:o)>>int(:b)>=->s{[s.a,s.o,s.b]}) | int(:a)).r)
p "--------"
p ((((Match.new("123-456")>>int(:a)>>op(:o)>>int(:b)>=->s{[s.a,s.o,s.b]}) | int(:a))>>op2(:o)).r)
p ((((Match.new("123-456")>>int(:a)>>op(:o)>>int(:b)>=->s{[s.a,s.o,s.b]}) | int(:a))>>op2(:o)>>int(:b)>=->s{[s.a,s.o,s.b]}).r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment