-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcounter.cr
More file actions
45 lines (39 loc) · 945 Bytes
/
counter.cr
File metadata and controls
45 lines (39 loc) · 945 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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