Skip to content

Commit 88fbfa1

Browse files
committed
added prog and prog2 examples
1 parent 0c39a58 commit 88fbfa1

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,4 @@ in a controlled repository now.
2929
* `phantom.rs`: phantom type example
3030
* `deref.rs`: deref trait example
3131
* `from.rs`: from / try_from trait example
32+
* `prog.rs`, `prog2.rs`: state machine examples using closures

prog.rs

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
struct State {
2+
r: [i32;2],
3+
pc: usize,
4+
}
5+
6+
type Op = fn(State) -> State;
7+
8+
impl State {
9+
fn run(mut self, prog: &[Op]) -> i32 {
10+
while self.pc < prog.len() {
11+
let pc = self.pc;
12+
self = prog[pc](self);
13+
self.pc += 1;
14+
}
15+
self.r[0]
16+
}
17+
}
18+
19+
fn add(mut state: State) -> State {
20+
state.r[0] += state.r[1];
21+
state
22+
}
23+
24+
fn sub(mut state: State) -> State {
25+
state.r[0] -= state.r[1];
26+
state
27+
}
28+
29+
30+
fn main() {
31+
let state = State { r: [0, 1], pc: 0 };
32+
let prog = [add, add, sub, add];
33+
println!("{}", state.run(&prog));
34+
}

prog2.rs

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
struct State {
2+
r: [i32;4],
3+
pc: usize,
4+
}
5+
6+
type Op = Box<dyn Fn(State) -> State>;
7+
8+
impl State {
9+
fn run(mut self, prog: &[Op]) -> i32 {
10+
while self.pc < prog.len() {
11+
let pc = self.pc;
12+
self = prog[pc](self);
13+
self.pc += 1;
14+
}
15+
self.r[0]
16+
}
17+
}
18+
19+
fn add(mut state: State) -> State {
20+
state.r[0] += state.r[1];
21+
state
22+
}
23+
24+
fn sub(mut state: State) -> State {
25+
state.r[0] -= state.r[1];
26+
state
27+
}
28+
29+
fn mov(from: usize, to: usize) -> Op {
30+
Box::new(move |mut state: State| -> State {state.r[to] = state.r[from]; state})
31+
}
32+
33+
34+
fn main() {
35+
let state = State { r: [0, 1, 0, 0], pc: 0 };
36+
let add = || Box::new(add);
37+
let sub = || Box::new(sub);
38+
let prog = [add(), mov(0, 1), add(), mov(0, 1), add(), mov(3,1), sub()];
39+
println!("{}", state.run(&prog));
40+
}

0 commit comments

Comments
 (0)