Skip to content

Instantly share code, notes, and snippets.

@rsc
Created July 12, 2023 23:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rsc/5908886288b741b847a83c0c6597c690 to your computer and use it in GitHub Desktop.
Save rsc/5908886288b741b847a83c0c6597c690 to your computer and use it in GitHub Desktop.
tree comparison using lua coroutines
#!/usr/local/bin/lua
function T(l, v, r)
return {left = l, value = v, right = r}
end
function visit(t)
if t ~= nil then -- note: ~= is "not equal"
visit(t.left)
coroutine.yield(t.value)
visit(t.right)
end
end
function cmp(t1, t2)
co1 = coroutine.create(visit)
co2 = coroutine.create(visit)
while true
do
ok1, v1 = coroutine.resume(co1, t1)
ok2, v2 = coroutine.resume(co2, t2)
if ok1 ~= ok2 or v1 ~= v2 then
return false
end
if not ok1 and not ok2 then
return true
end
end
end
function cmp2(t1, t2)
next1 = coroutine.wrap(function() visit(t1) end)
next2 = coroutine.wrap(function() visit(t2) end)
while true
do
v1 = next1()
v2 = next2()
if v1 ~= v2 then
return false
end
if v1 == nil and v2 == nil then
return true
end
end
end
t1 = T(T(T(nil, 1, nil), 2, T(nil, 3, nil)), 4, T(nil, 5, nil))
t2 = T(nil, 1, T(nil, 2, T(nil, 3, T(nil, 4, T(nil, 5, nil)))))
t3 = T(nil, 1, T(nil, 2, T(nil, 3, T(nil, 4, T(nil, 6, nil)))))
print(cmp(t1, t2), cmp(t1, t3))
print(cmp2(t1, t2), cmp2(t1, t3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment