Created
July 12, 2017 08:51
-
-
Save koji-k/fc5f344b53b8edfd4ad1cc6f28960392 to your computer and use it in GitHub Desktop.
インタープリタのサンプル?
This file contains 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
trait GOperator { | |
abstract execute(List args) | |
} | |
class AddOperator implements GOperator { | |
Object execute(List args) { | |
args.sum() | |
} | |
} | |
class MinusOperator implements GOperator { | |
Object execute(List args) { | |
args.inject {l, r -> l - r} | |
} | |
} | |
class MyLanguage { | |
Map operators = [ | |
"+": new AddOperator(), | |
"-": new MinusOperator() | |
] | |
Object parse(String sourceCode) { | |
new GroovyShell().evaluate(sourceCode) | |
} | |
Object execute(Object myLanguageCode) { | |
String rawOpe = myLanguageCode.head() | |
GOperator op = operators[rawOpe] | |
op.execute(myLanguageCode.tail()) | |
} | |
} | |
def engine = new MyLanguage() | |
def parsedCode = engine.parse('["+", 1, 2]') | |
assert engine.execute(parsedCode) == 3 | |
parsedCode = engine.parse('["-", 1, 2, 3]') | |
assert engine.execute(parsedCode) == -4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment