Skip to content

Commit 8a8318b

Browse files
committed
updated prog and prog2
1 parent 15ddf49 commit 8a8318b

File tree

2 files changed

+27
-24
lines changed

2 files changed

+27
-24
lines changed

prog.rs

+7-8
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
struct State {
1+
struct CpuState {
22
r: [i32;2],
33
pc: usize,
44
}
55

6-
type Op = fn(State) -> State;
6+
type Op = fn(CpuState) -> CpuState;
77

8-
impl State {
8+
impl CpuState {
99
fn run(mut self, prog: &[Op]) -> i32 {
1010
while self.pc < prog.len() {
1111
let pc = self.pc;
@@ -16,19 +16,18 @@ impl State {
1616
}
1717
}
1818

19-
fn add(mut state: State) -> State {
19+
fn add(mut state: CpuState) -> CpuState {
2020
state.r[0] += state.r[1];
2121
state
2222
}
2323

24-
fn sub(mut state: State) -> State {
24+
fn sub(mut state: CpuState) -> CpuState {
2525
state.r[0] -= state.r[1];
2626
state
2727
}
2828

29-
3029
fn main() {
31-
let state = State { r: [0, 1], pc: 0 };
30+
let state = CpuState { r: [0, 1], pc: 0 };
3231
let prog = [add, add, sub, add];
3332
println!("{}", state.run(&prog));
34-
}
33+
}

prog2.rs

+20-16
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
struct State {
1+
struct CpuState {
22
r: [i32;4],
33
pc: usize,
44
}
55

6-
type Op = Box<dyn Fn(State) -> State>;
6+
type Op = Box<dyn Fn(CpuState) -> CpuState>;
77

8-
impl State {
8+
impl CpuState {
99
fn run(mut self, prog: &[Op]) -> i32 {
1010
while self.pc < prog.len() {
1111
let pc = self.pc;
@@ -16,25 +16,29 @@ impl State {
1616
}
1717
}
1818

19-
fn add(mut state: State) -> State {
20-
state.r[0] += state.r[1];
21-
state
19+
fn add() -> Op {
20+
Box::new(|mut state: CpuState| -> CpuState {
21+
state.r[0] += state.r[1];
22+
state
23+
})
2224
}
2325

24-
fn sub(mut state: State) -> State {
25-
state.r[0] -= state.r[1];
26-
state
26+
fn sub() -> Op {
27+
Box::new(|mut state: CpuState| -> CpuState {
28+
state.r[0] -= state.r[1];
29+
state
30+
})
2731
}
2832

2933
fn mov(from: usize, to: usize) -> Op {
30-
Box::new(move |mut state: State| -> State {state.r[to] = state.r[from]; state})
34+
Box::new(move |mut state: CpuState| -> CpuState {
35+
state.r[to] = state.r[from];
36+
state
37+
})
3138
}
3239

33-
3440
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));
41+
let state = CpuState { r: [0, 1, 0, 0], pc: 0 };
42+
let prog = &[add(), mov(0, 1), add(), mov(0, 1), add(), mov(3, 1), sub()];
43+
println!("{}", state.run(prog));
4044
}

0 commit comments

Comments
 (0)