-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpropositional_logic.ts
195 lines (180 loc) · 5.46 KB
/
propositional_logic.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { assertEquals } from 'https://deno.land/[email protected]/testing/asserts.ts';
export function evaluate(expression: string, values: Map<string, boolean>) {
return evaluatePropositionalLogicRPN(
parsePropositionalLogicRPN(expression),
values
);
}
export function preprocessExpression(expression: string) {
return expression
.replaceAll(/equal|equiv|=|↔|<->/gi, '≡')
.replaceAll(/and|&/gi, '∧')
.replaceAll(/or|\|/gi, '∨')
.replaceAll(/imply|implies|->/gi, '→')
.replaceAll(/not|!|~|-/gi, '¬')
.replaceAll(/\s/gi, '');
}
const Tokens = {
isOperator: (token: string) => ['¬', '∧', '∨', '→', '≡'].includes(token),
isOperand: (token: string) => /[a-z]/i.test(token),
getPrecedence: (token: string) => Tokens.precedences.get(token)!,
precedences: new Map([
['¬', 3],
['∧', 2],
['∨', 2],
['→', 1],
['≡', 0],
]),
};
// parse propositional logic expression into reverse polish notation
function parsePropositionalLogicRPN(expression: string): string[] {
const stack: string[] = [];
const output: string[] = [];
// tokenize expression
for (const char of expression) {
if (Tokens.isOperand(char)) {
// handle operands
output.push(char);
} else if (Tokens.isOperator(char)) {
// handle operators
while (
stack.length > 0 &&
Tokens.isOperator(stack[stack.length - 1]) &&
Tokens.getPrecedence(char) <=
Tokens.getPrecedence(stack[stack.length - 1])
) {
// while the precedence of the operator on the top of the stack is
// greater than or equal to the precedence of the current operator,
// pop the operator from the stack and add it to the output.
output.push(stack.pop()!);
}
stack.push(char);
} else if (char === '(') {
stack.push(char);
} else if (char === ')') {
while (stack[stack.length - 1] !== '(') {
output.push(stack.pop()!);
}
stack.pop();
} else {
throw new Error(`Invalid character: ${char}`);
}
}
while (stack.length > 0) {
output.push(stack.pop()!);
}
return output;
}
// evaluate propositional logic expression in reverse polish notation
function evaluatePropositionalLogicRPN(
rpn: string[],
values: Map<string, boolean>
): boolean {
const stack: boolean[] = [];
for (const token of rpn) {
if (Tokens.isOperand(token)) {
// handle operands
stack.push(values.get(token)!);
} else if (Tokens.isOperator(token)) {
if (['¬'].includes(token)) {
// handle unary operators
stack.push(!stack.pop()!);
} else {
// handle binary operators
const rhs = stack.pop()!;
const lhs = stack.pop()!;
switch (token) {
case '∧':
stack.push(lhs && rhs);
break;
case '∨':
stack.push(lhs || rhs);
break;
case '→':
stack.push(!lhs || rhs);
break;
case '≡':
stack.push(lhs === rhs);
break;
default:
throw new Error(`Invalid token: ${token}`);
}
}
} else {
throw new Error(`Invalid token: ${token}`);
}
}
if (stack.length !== 1) {
throw new Error('Invalid RPN');
}
return stack.pop()!;
}
// tests
Deno.test('parse RPN', () => {
assertEquals(parsePropositionalLogicRPN(preprocessExpression('p and q')), [
'p',
'q',
'∧',
]);
assertEquals(
parsePropositionalLogicRPN(preprocessExpression('!p | (p & q)')),
['p', '¬', 'p', 'q', '∧', '∨']
);
assertEquals(parsePropositionalLogicRPN(preprocessExpression('p -> q')), [
'p',
'q',
'→',
]);
assertEquals(parsePropositionalLogicRPN(preprocessExpression('p = !q')), [
'p',
'q',
'¬',
'≡',
]);
assertEquals(
parsePropositionalLogicRPN(preprocessExpression('!p | q = p -> q')),
['p', '¬', 'q', '∨', 'p', 'q', '→', '≡']
);
});
Deno.test('evaluate RPN', () => {
assertEquals(
evaluatePropositionalLogicRPN(
['p', 'q', '∧'],
new Map([
['p', true],
['q', false],
])
),
false
);
assertEquals(
evaluatePropositionalLogicRPN(
['p', 'q', '→'],
new Map([
['p', true],
['q', false],
])
),
false
);
assertEquals(
evaluatePropositionalLogicRPN(
['p', 'q', '¬', '≡'],
new Map([
['p', true],
['q', false],
])
),
true
);
assertEquals(
evaluatePropositionalLogicRPN(
['p', '¬', 'q', '∨', 'p', 'q', '→', '≡'],
new Map([
['p', false],
['q', true],
])
),
true
);
});