Skip to content

Instantly share code, notes, and snippets.

@brandonwillard
Created July 22, 2019 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonwillard/e3d985ee3cc8b43d9668b719a5c72277 to your computer and use it in GitHub Desktop.
Save brandonwillard/e3d985ee3cc8b43d9668b719a5c72277 to your computer and use it in GitHub Desktop.
A Python example that uses miniKanren to substitute elements in a list/graph structure.
from unification import var
from kanren import run, eq
# Logical conjunction
from kanren import lall as lconj
# Logical disjunction
from kanren import lany as ldisj
# `conde((a, b), (c, d), ...)` == `ldisj(lconj(a, b), lconj(c, d), ...)`
from symbolic_pymc.relations.graph import graph_applyo
def replace_oneo(in_obj, out_lv):
g = lconj(eq(in_obj, 1),
eq(out_lv, "one"))
return g
def replace_twoo(in_obj, out_lv):
g = lconj(eq(in_obj, 2),
eq(out_lv, "two"))
return g
def number_to_wordo(in_obj, out_lv):
res = ldisj(replace_oneo(in_obj, out_lv),
replace_twoo(in_obj, out_lv))
return res
def numbers_to_words(in_obj):
"""Replace 1 with "one"."""
out_lv = var('output')
# Try returning all results by setting 1 -> 0; it should be
# slower for the nested lists!
res = run(1, out_lv,
graph_applyo(number_to_wordo, in_obj, out_lv))
return res
numbers_to_words(1)
numbers_to_words(2)
numbers_to_words([1])
numbers_to_words([2])
numbers_to_words([1, 2])
numbers_to_words([1, [1, 2]])
numbers_to_words([1, [1, [1, 2]]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment