Skip to content

Instantly share code, notes, and snippets.

@aj07mm
Created March 31, 2020 21:03
Show Gist options
  • Save aj07mm/0f4887cb1a9b9b298feca3e023883b7b to your computer and use it in GitHub Desktop.
Save aj07mm/0f4887cb1a9b9b298feca3e023883b7b to your computer and use it in GitHub Desktop.
transducer.py
"""
user=> (transduce (map inc) + 0 [1 2 3])
9
user=> (transduce (map inc) - 10 [1 2 3])
-1
"""
def transduce(transducer, reducer, iterable, memo):
return reduce(transducer(reducer), iterable, memo)
def transducer(fn):
def wrapper(a, b):
return fn(a, b) + 1
return wrapper
def reducer(acc, n):
return acc + n
print(transduce(transducer, reducer, [1, 2, 3], 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment