Last active
May 19, 2023 09:20
-
-
Save SegFaultAX/10941721 to your computer and use it in GitHub Desktop.
clojure.walk in Python
This file contains hidden or 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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)