-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
134 lines (119 loc) · 2.87 KB
/
mod.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
type Unary = (p: boolean) => boolean
type Binary = (p: boolean, q: boolean) => boolean
const fn: Record<string, Unary | Binary> = {
AND: (p, q) => p && q,
OR: (p, q) => p || q,
IF: (p, q) => !p || q,
IFF: (p, q) => p == q,
NOT: (p => !p) as Unary,
}
const char = {
AND: "&",
OR: "|",
IF: "→",
IFF: "↔",
NOT: "~",
}
const tokenize =
(str: string) =>
str
.replaceAll("<->", char.IFF)
.replaceAll("->", char.IF)
.replaceAll("|", char.OR)
.replaceAll("&", char.AND)
.replaceAll("!", char.NOT)
const isOp =
(c: string) =>
Object.values(char).includes(c)
type Expr =
| string
| [string, Expr]
| [string, Expr, Expr]
const lex =
(tokens: string) => {
const ops: string[] = []
const vars: Expr[] = []
const flush = () => {
while (ops.length != 0) {
if (ops[ops.length-1] == "(") {
ops.pop()
while (ops[ops.length-1] == char.NOT) {
vars.push([ops.pop()!, vars.pop()!])
}
break
}
if (ops[ops.length-1] == char.NOT) {
vars.push([ops.pop()!, vars.pop()!])
} else {
vars.push([ops.pop()!, ...vars.splice(-2) as [Expr, Expr]])
}
}
}
;[...tokens].forEach(token => {
// console.log(token, ops, vars)
if (isOp(token) || token == "(") ops.push(token)
else if (/[a-zA-Z]/.test(token)) {
ops.push("(")
vars.push(token)
flush()
}
else if (token == ")") {
flush()
}
})
flush()
return vars[0]
}
const getOpName =
(op: string) =>
Object.entries(char).find(([k, v]) => v == op)![0]
const strify =
(expr: Expr): string => {
if (typeof expr == "string")
return expr
const [op, ...exprs] = expr
return `${getOpName(op)}(${exprs.map(strify).join(",")})`
}
import { makeContainer } from "https://deno.land/x/[email protected]/mod.ts"
const $ = makeContainer({})
const fnify =
(expr: Expr): (val: Record<string, boolean>) => boolean => {
if (typeof expr == "string")
return val => val[expr]
const [op, ...exprs] = expr
return val => $(val)
.pipe(val => fn[getOpName(op)](
...<[boolean, boolean]>exprs.map(expr => fnify(expr)(val))
))
.bypass(tf => console.log(
strify(expr), "=", tf,
))
.get()
}
{
const $ = makeContainer({
strify,
fnify,
lex,
tokenize,
})
console.log(
$("~((p|~q)->r)")
.tokenize()
.lex()
.strify()
.get()
)
console.log(
$("~((p|~q)->r)")
.tokenize()
.lex()
.fnify()
.get()
({
p: true,
q: true,
r: true,
})
)
}