forked from gcanti/fp-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathixIO.ts
82 lines (67 loc) · 1.91 KB
/
ixIO.ts
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { IO } from '../src/IO'
import { IxIO } from '../src/IxIO'
/*
Usage
Based on State Machines All The Way Down
An Architecture for Dependently Typed Applications
https://eb.host.cs.st-andrews.ac.uk/drafts/states-all-the-way.pdf
by Edwin Brady
*/
//
// finite state machine
//
// By defining this state machine in a type, we can ensure that any sequence
// of operations which type checks is a valid sequence of operations on a door.
// The door can be open or closed
export type DoorState = 'Open' | 'Closed'
//
// operations
//
// A represents the return type of the operation
// I represents the input state (the precondition)
// O represents output state (the postcondition)
export class Operation<I extends DoorState, O extends DoorState, A> extends IxIO<I, O, A> {}
class Open extends Operation<'Closed', 'Open', void> {
constructor() {
super(
new IO(() => {
console.log(`Opening the door`)
})
)
}
}
class Close extends Operation<'Open', 'Closed', void> {
constructor() {
super(
new IO(() => {
console.log(`Closing the door`)
})
)
}
}
class RingBell extends Operation<'Closed', 'Closed', void> {
constructor() {
super(
new IO(() => {
console.log(`Ringing the bell`)
})
)
}
}
// tip: decomment the following lines to see the static errors
// error: Type '"Open"' is not assignable to type '"Closed"'
// if you open the door, you must close it
// const x1: Operation<'Closed', 'Closed', void> = new Open()
// ok
export const x2: Operation<'Closed', 'Closed', void> = new Open().ichain(() => new Close())
// error: Type '"Closed"' is not assignable to type '"Open"'
// you can't ring the bell when the door is open
// const x3 = new Open().ichain(() => new RingBell())
// ok
export const x4 = new Open().ichain(() => new Close()).ichain(() => new RingBell())
x4.run()
/*
Opening the door
Closing the door
Ringing the bell
*/