-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
67 lines (51 loc) · 1.5 KB
/
main.c
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ActionI {
int type;
int payload;
};
struct ActionI * newAction(int type, int payload) {
struct ActionI *self = (struct ActionI *) malloc(sizeof(struct ActionI));
self->type = type;
self->payload = payload;
return self;
}
struct Store {
int (*reducer)(int state, struct ActionI *);
void (*dispatch)(struct Store *, struct ActionI *);
int cont;
};
struct Store * newStore(
int (*reducer)(int state, struct ActionI *),
void (*dispatch)(struct Store *, struct ActionI *),
int cont
) {
struct Store *self = (struct Store *)malloc(sizeof(struct Store));
self->cont = cont;
self->reducer = reducer;
self->dispatch = dispatch;
return self;
}
void dispatch(struct Store *store, struct ActionI *action) {
int newState = store->reducer(store->cont, action);
store->cont = newState;
}
int reducer(int state, struct ActionI *action) {
switch (action->type){
case 1:
return state + action->payload;
case 0:
return state - action->payload;
default:
return state;
}
}
int main() {
struct ActionI *add = (struct ActionI *) newAction(1, 1);
struct Store *store = (struct Store *) newStore(&reducer, &dispatch, 0);
printf("inicial state: %d\n", store->cont);
store->dispatch(store, add);
printf("final state: %d\n", store->cont);
return 0;
}