Permalink
Cannot retrieve contributors at this time
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
45 lines (39 sloc)
945 Bytes
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
require "dataclass" | |
require "../lib/runtime" | |
module Counter | |
dataclass CounterState{value : Int32} | |
abstract struct Op; end | |
record Plus < Op | |
record Minus < Op | |
record Er, reason : String | |
def self.parse(input : String) : Op | Er | |
if input == "+" | |
Plus.new | |
elsif input == "-" | |
Minus.new | |
else | |
Er.new("Unknown operation") | |
end | |
end | |
def self.interpret(state : CounterState, op : Op) : {CounterState, String} | |
new_val = case op | |
when Plus | |
state.value + 1 | |
when Minus | |
state.value - 1 | |
else | |
raise Exception.new("Unknown operation") | |
end | |
{state.copy(value: new_val), "count: #{new_val}"} | |
end | |
def self.runtime | |
state = CounterState.new(0) | |
parser_fn = ->Counter.parse(String) | |
interpreter_fn = ->Counter.interpret(CounterState, Op) | |
Runtime(CounterState, Op, Er) | |
.new(state, parser_fn, interpreter_fn) | |
end | |
def self.version | |
"0.0.1" | |
end | |
end |