Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Last active May 19, 2023 09:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SegFaultAX/10941721 to your computer and use it in GitHub Desktop.
Save SegFaultAX/10941721 to your computer and use it in GitHub Desktop.
clojure.walk in Python
from functools import partial
def identity(e):
return e
def walk(inner, outer, coll):
if isinstance(coll, list):
return outer([inner(e) for e in coll])
elif isinstance(coll, dict):
return outer(dict([inner(e) for e in coll.iteritems()]))
elif isinstance(coll, tuple):
return outer([inner(e) for e in coll])
else:
return outer(coll)
def prewalk(fn, coll):
return walk(partial(prewalk, fn), identity, fn(coll))
def postwalk(fn, coll):
return walk(partial(postwalk, fn), fn, coll)
def prewalk_demo(coll):
def prn(e):
print "Walked:", e
return e
return prewalk(prn, coll)
def postwalk_demo(coll):
def prn(e):
print "Walked:", e
return e
return postwalk(prn, coll)
@mourginakis
Copy link

mourginakis commented May 19, 2023

Amazing thank you.
Needs update for python3:
10. return outer(dict([inner(e) for e in coll.iteritems()])) => return outer(dict([inner(e) for e in coll.items()]))
24. print "Walked:", e => print("Walked:", e)
30. print "Walked:", e => print("Walked:", e)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment