~nch/gamelog

ref: 75432213d3972f26c03ef636da68ed482f0ac908 gamelog/datalog.lua -rw-r--r-- 12.9 KiB View raw
75432213 — nc refactoring debug code out a bit 5 months ago
                                                                                
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
local fun = require 'fun'
local tuple = require 'tuple'
local set = require 'set'

-- FIXME: create an env type that's an array of tuples, and is immutable
-- FIXME: write a lookup function for the env

-- term = constant | variable
-- atom = (name, term, ...)
--   car(atom) = name
--   cdr(atom) = [terms]
-- rule = atom :- atom, ...
-- program = rule ...

local pprint = require 'pprint'
pprint.setup {use_tostring = true}

function is_empty(tbl)
    return next(tbl) == nil
end

function negate(f) --> func
    return function(...) return not f(...) end
end

function clone_table(a)
    local r = {}
    for k, v in pairs(a) do
        r[k] = v
    end
    return r
end

function is_var(x)
    return type(x) == 'string' and string.sub(x, 1, 1) == '@'
end

function chase(env, v)
    if is_var(v) then
        if env[v] ~= nil then
            return chase(env, env[v])
        end
    end
    return v
end

function unify_term(env, a, b)
    local t1 = chase(env, a)
    local t2 = chase(env, b)
    if is_var(t1) and not is_var(t2) then
        -- HACK: should be immutable data structure
        env = clone_table(env)
        env[t1] = t2
        return env
    elseif is_var(t2) and not is_var(t1) then
        -- HACK: should be immutable data structure
        env = clone_table(env)
        env[t2] = t1
        return env
    elseif t1 == '_' or t2 == '_' then -- the "don't care" value
        return env
    elseif t1 == t2 then
        return env
    end
end

local function test_unify_term()
    assert(unify_term({['@a'] = 1}, '@a', 1) ~= nil)
    assert(unify_term({}, '@a', 1)['@a'] == 1)
    assert(unify_term({}, 1, '@a')['@a'] == 1)
    assert(unify_term({}, 1, 1) ~= nil)
    assert(unify_term({}, 'a', 'a') ~= nil)
    assert(unify_term({}, '_', 'a') ~= nil)
    assert(unify_term({}, '@a', '@a') ~= nil)
    assert(unify_term({}, 1, 2) == nil)
end

function unify(env, a, b) --> env
    if type(a) == 'table' and type(b) == 'table' then
        if (#a ~= #b) then return nil end
        local r = {}
        for _, x, y in fun.zip(a, b) do
            local u = unify(env, x, y)
            if u == nil then
                return nil
            else
                for k, v in pairs(u) do
                    r[k] = v
                end
                -- ehh... not my finest work
                env = u
            end
        end
        return r
    else
        return unify_term(env, a, b)
    end
    return env
end

local function test_unify()
    assert(is_eq(unify({}, {'a', 'b', 'c'}, {'a', 'b', 'c'}), {}))
    assert(is_eq(unify({}, {'a', {'b'}, 'c'}, {'a', {'b'}, 'c'}), {}))
    assert(is_eq(unify({}, {'@x', '@y', '@z'}, {'a', 'b', 'c'}), {['@x'] = 'a', ['@y'] = 'b', ['@z'] = 'c'}))
    assert(unify({}, {'@x', '@y', '@x'}, {'a', 'b', 'c'}) == nil, pprint.pformat(unify({}, {'@x', '@y', '@x'}, {'a', 'b', 'c'})))
    assert(is_eq(unify({}, {'@x', '@y', '@x'}, {'a', 'b', 'a'}), {['@x'] = 'a', ['@y'] = 'b'}))
end


local database = {}

function check_rule(head, ...)
    local vs = {}
    for _, t in pairs(fun.cdr(head):totable()) do
        if is_var(t) then
            vs[t] = 0
        end
    end
    for _, p in pairs({...}) do
        for _, t in pairs(fun.cdr(p):totable()) do
            if is_var(t) and vs[t] ~= nil then
                vs[t] = vs[t] + 1
            end
        end
    end
    for k, v in pairs(vs) do
        if v == 0 then
            error('variable defined in head, but not used in body: ' .. k)
        end
    end
end

local function test_check_rule()
    check_rule(
        tuple('grandpar', '@z', '@x'),
        --
        tuple('par', '@z', '@y'),
        tuple('par', '@y', '@x')
    )

    local status, err = pcall(function()
        check_rule(
            tuple('bad-rule', '@z', '@x'), -- @z doesn't get used
            --
            tuple('par', '@x', '@y')
        )
    end)

    assert(status == false)
    assert(err ~= nil and string.match(err, 'defined in head'))
    assert(err ~= nil and string.match(err, 'not used in body'))
    assert(err ~= nil and string.match(err, '@z'))
end

function substitute(env, atom) --> atom
    -- car(atom) = atom name
    -- cdr(atom) = atom terms
    return tuple(fun.car(atom),
        table.unpack(fun.map(function(x)
            if is_var(x) and env[x] ~= nil then
                return env[x]
            else
                return x
            end
        end, fun.cdr(atom)):totable()))
end


local function test_substitute()
    assert(is_eq(fun.cdr(substitute({['@x'] = 'v'}, tuple('a', '@x', 'y'))):totable(), {'v', 'y'}))
end

function flat_map(f, ts)
    if next(ts) == nil then return fun.iter({}) end -- YIKES! why you gotta be this way, lua?
    return fun.chain(table.unpack(fun.totable(fun.map(f, ts))))
end

local function test_flat_map()
    assert(is_eq(fun.totable(flat_map(function(x) return {x} end, {1,2,3})), {1,2,3}))
    assert(is_eq(fun.totable(flat_map(function(x)
        if x % 2 ~= 0 then
            return {x}
        end
        return {}
    end, {1,2,3})), {1,3}))
end

function eval_atom(db, envs, atom) --> [env]
    return flat_map(
        function(env)
            local a = substitute(env, atom)
            local extension = fun.map(function (x)
                return unify(env, fun.cdr(a):totable(), fun.cdr(x):totable()) or {}
            end, db):filter(negate(is_empty)):totable()
            return extension
        end, envs):totable()
end

local function test_eval_atom()
    local r1 = eval_atom(set({
        tuple('par', 'ann', 'bob'),
        tuple('par', 'ann', 'jane')
    }),
    {{}},
    tuple('par', 'ann', '@x'))
    assert(is_eq(r1,
        {{['@x'] = 'bob'}, {['@x'] = 'jane'}}),
        'got ' .. pprint.pformat(r1))

    local r2 = eval_atom(set({
        tuple('par', 'ann', 'bob', 'bob'),
        tuple('par', 'ann', 'jane', 'joe')
    }),
    {{}},
    tuple('par', 'ann', '@x', '@x'))
    assert(is_eq(r2, {{['@x'] = 'bob'}}), 'got ' .. pprint.pformat(r2))

    local r3 = eval_atom(set({
        tuple('par', 'ann', 'bob'),
        tuple('par', 'ann', 'jane')
    }),
    {{}},
    tuple('par', '@x', '@y'))
    assert(is_eq(r3, {{['@x'] = 'ann', ['@y'] = 'bob'}, {['@x'] = 'ann', ['@y'] = 'jane'}}), 'got ' .. pprint.pformat(r3))

    local r4 = eval_atom(set({
        tuple('par', 'ann', 'bob'),
        tuple('par', 'carla', 'bob')
    }),
    {{['@a'] = 'ann'}},
    tuple('par', '@a', '@b'))
    assert(is_eq(r4, {{['@a'] = 'ann', ['@b'] = 'bob'}}), 'got ' .. pprint.pformat(r4))
end

function reverse(lst)
    local r = {}
    for i=1,#lst do
        r[i] = lst[#lst-(i-1)]
    end
    return r
end

local function test_reverse()
    assert(is_eq(reverse({1,2,3}), {3,2,1}), pprint.pformat(reverse({1,2,3})))
    assert(is_eq(reverse({1,3}), {3,1}))
    assert(is_eq(reverse({}), {}))
end

function eval_rule(db, rule) --> new_facts:db
    local head = fun.car(rule)
    local body = fun.cdr(rule):totable()
    local walk = fun.foldl(function(agg, atom)
        return(eval_atom(db, agg, atom))
    end, {{}}, reverse(body))
    return fun.map(function(t)
        return substitute(t, head)
    end, walk):totable()
end

local function test_eval_rule()
    local r = eval_rule(set({
        tuple('par', 'adam', 'bob'),
        tuple('par', 'bob', 'caleb'),
        tuple('par', 'caleb', 'david'),
    }),
    {
        tuple('grandpar', '@gparent', '@gchild'),
        --
        tuple('par', '@gparent', '@parent'),
        tuple('par', '@parent', '@gchild')
    })
    assert(set(r) == set({
        tuple('grandpar', 'bob', 'david'),
        tuple('grandpar', 'adam', 'caleb')
    }), 'got ' .. pprint.pformat(r))
end

function query(db, goal, env)
    return flat_map(function(x)
        local r = unify(env or {}, goal, x)
        if r then return {r} else return {} end
    end, db):totable()
end

function query_record(db, goal, env)
    return flat_map(function(x)
        local r = unify(env or {}, goal, x)
        if r then return {x} else return {} end
    end, db):totable()
end

function update(db, goal, f, env)
    local recs = query_record(db, goal, env)
    for i=1, #recs do
        db:remove(recs[i])
        db:add(f(recs[i]))
    end
end

local function test_update()
    local db = set({tuple('a', 1), tuple('b', 2)})
    update(db, {'a', '_'}, function(x) return x:update(2, x[2] + 1) end)
    assert(db[tuple('a', 2)] == true)
end

-- arbitrary, expects at least 1 result
function query_single(db, goal)
    local q = query(db, goal)
    if #q > 0 then
        return q[1]
    end
    error('not found for goal ' .. pprint.pformat(goal))
end

local function test_query()
    local r = query({tuple('a', 'b', 'c'), tuple('c', 'd', 'e')}, tuple('a', '@x', 'c'))
    assert(r[1]['@x'] == 'b', pprint.pformat(r))
    local r = query({tuple('a', 'b', 'c'), tuple('a', 'd', 'c')}, tuple('a', '@x', 'c'))
    assert(r[1]['@x'] == 'b', pprint.pformat(r))
    assert(r[2]['@x'] == 'd', pprint.pformat(r))
    local r = query({tuple('a', 'b', 'c'), tuple('a', 'c', 'c')}, tuple('a', '@x', '@x'), {})
    assert(#r == 1)
    assert(r[1]['@x'] == 'c', pprint.pformat(r))
end

function query_(db, goals, env)
    if env == nil then
        return query_(db, goals, {})
    elseif is_empty(goals) then
        return {env}
    else
        return flat_map(
        function(e)
            return query_(db, fun.cdr(goals):totable(), e)
        end,
        query(db, fun.car(goals), env)):totable()
    end
end

local function test_query_()
    local r = query_(
        {
            tuple('father', 'zues', 'cronos'),
            tuple('father', 'cronos', 'uranus')
        },
        {
            tuple('father', '@son', '@father'),
            tuple('father', '@father', '@grandfather')
        }
    )
    assert(#r == 1)
    assert(r[1]['@son'] == 'zues', pprint.pformat(r))
    assert(r[1]['@father'] == 'cronos', pprint.pformat(r))
    assert(r[1]['@grandfather'] == 'uranus', pprint.pformat(r))
end

function naive_query(db, rules, goals)
    -- TODO: check_rule()
    for i=1, #rules do
        check_rule(table.unpack(rules[i]))
    end
    local function naive(db, rules)
        assert(type(rules) == 'table')
        local facts = set(flat_map(function(r) return eval_rule(db, r) end, rules):totable())
        local db_ = db + facts
        if(db == db_) then
            return db_
        else
            return naive(db_, rules)
        end
    end

    return query_(naive(db, rules), goals)
end

local function test_naive()
    local initial_db = set({
        tuple('mother', 'dorthy', 'james'),
        tuple('father', 'charles', 'george'),
        tuple('mother', 'ann', 'charles')
    })
    local r = naive_query(initial_db,
    {
        {
            tuple('par', '@x', '@y'),
            --
            tuple('mother', '@x', '@y')
        },
        {
            tuple('par', '@x', '@y'),
            --
            tuple('father', '@x', '@y')
        },
        {
            tuple('grandpar', '@x', '@y'),
            --
            tuple('par', '@x', '@z'),
            tuple('par', '@z', '@y')
        },
    },
    {tuple('grandpar', '@grandpar', '@grandchild')})
    assert(#r == 1)
    assert(r[1]['@grandpar'] == 'ann')
    assert(r[1]['@grandchild'] == 'george')

    local initial_db = set({
        tuple('edge', 'a', 'b'),
        tuple('edge', 'b', 'c'),
        tuple('edge', 'c', 'd'),
        tuple('edge', 'd', 'a'),
    })

    -- classic edge/path example
    local r = naive_query(initial_db,
    {
        {
            tuple('path', '@x', '@y'),
            --
            tuple('edge', '@x', '@y'),
        },
        {
            tuple('path', '@x', '@y'),
            --
            tuple('edge', '@x', '@t'),
            tuple('path', '@t', '@y'),
        },
    },
    {tuple('path', '@a', '@b')})
    assert(#r == 16)

    -- test to make sure rules are getting checked (i.e. all vars in head are used)
    local status, _ = pcall(function()
        naive_query(initial_db,
        {
            {
                tuple('bad_rule', '@x', '@y'),
                --
                tuple('edge', '@x', '@x')
            }
        },
        {tuple('bad_rule', 'a', 'b')})
    end)
    assert(status == false)
end

function insert(db, fact)
    local t = tuple(table.unpack(fact))
    fun.foreach(fun.cdr(t), function(x) assert(not is_var(x)) end)
    db:add(t)
end

function delete(db, fact)
    db:remove(fact)
end

function max(env, k)
    local max = 0
    for i=1, #env do
        if env[i][k] > max then
            max = env[i][k]
        end
    end
    return max
end

local function test_max()
    local test_db = set({{'a', 4}, {'b', 5}, {'a', 1}})
    assert(is_eq(max(query(test_db, {'a', '@i'}), '@i'), 4))
end

function predicate(db, name)
    return setmetatable({
        query = function(...)
            return query(db, {name, ...})
        end,
        insert = function(...)
            insert(db, {name, ...})
        end
    }, {
        __call = function(_, ...)
            return {name, ...}
        end
    })
end


-- TODO: implement comparisons
-- TODO: implement aggregate functions
-- TODO: implement non-naive querying
-- TODO: implement assertions/retractions