Created
July 22, 2019 02:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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