SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
@sixty_north
Understanding Transducers
Through Python
1
Austin Bingham
@austin_bingham
Sunday, January 25, 15
237
“Transducers are coming”
Rich Hickeyhttp://blog.cognitect.com/blog/2014/8/6/transducers-are-coming
Photo: Howard Lewis Ship under CC-BY
Sunday, January 25, 15
Functions which transform reducers
What is a transducer?
‣ Reducer (reducing function)
• Any function we can pass to reduce(reducer, iterable[, initial])
• (result, input) → result
• add(result, input)
reduce(add, [1, 2, 3], 0) → 6
‣ Transducer (transform reducer)
• A function which accepts a reducer, and transforms it in some way, and returns a
new reducer
• ((result, input) → result) → ((result, input) → result)
3
Sunday, January 25, 15
Transducers are a functional programming technique not restricted to Clojure
How does this relate to Python?
‣ Clojure implementation is the prototype/archetype
• Heavily uses anonymous functions
• Uses overloads on function arity for disparate purposes
• Complected with existing approaches
‣ Python implementation is pedagogical (but also useful)
• Explicit is better than implicit
• Readability counts!
• Has all the functional tools we need for transducers
• I’m a better Pythonista than Clojurist
4
Sunday, January 25, 15
5
Review
functional programming
tools in
Sunday, January 25, 15
6
my_filter(is_prime, my_map(prime_factors, range(32) ) )
iterable
sequence
sequence
Sunday, January 25, 15
7
def my_map(transform, iterable):
def map_reducer(sequence, item):
sequence.append(transform(item))
return sequence
return reduce(map_reducer, iterable, [])
def my_filter(predicate, iterable):
def filter_reducer(sequence, item):
if predicate(item):
sequence.append(item)
return sequence
return reduce(filter_reducer, iterable, [])
Sunday, January 25, 15
7
def my_map(transform, iterable):
def map_reducer(sequence, item):
sequence.append(transform(item))
return sequence
return reduce(map_reducer, iterable, [])
def my_filter(predicate, iterable):
def filter_reducer(sequence, item):
if predicate(item):
sequence.append(item)
return sequence
return reduce(filter_reducer, iterable, [])
reduce()
Sunday, January 25, 15
7
def my_map(transform, iterable):
def map_reducer(sequence, item):
sequence.append(transform(item))
return sequence
return reduce(map_reducer, iterable, [])
def my_filter(predicate, iterable):
def filter_reducer(sequence, item):
if predicate(item):
sequence.append(item)
return sequence
return reduce(filter_reducer, iterable, [])
reduce()
sequence.append()
Sunday, January 25, 15
7
def my_map(transform, iterable):
def map_reducer(sequence, item):
sequence.append(transform(item))
return sequence
return reduce(map_reducer, iterable, [])
def my_filter(predicate, iterable):
def filter_reducer(sequence, item):
if predicate(item):
sequence.append(item)
return sequence
return reduce(filter_reducer, iterable, [])
reduce()
sequence.append()
Empty list : ‘seed’
must be a mutable
sequence
Sunday, January 25, 15
8
>>> reduce(make_mapper(square), range(10), [])
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> reduce(make_filterer(is_prime), range(100), [])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97]
‣ make_mapper() and make_filterer() are not composable
‣ to square primes we would need to call reduce() twice
‣ this requires we store the intermediate sequence
‣ the reducers returned by make_mapper() and make_filterer()
depend on the seed being a mutable sequence e.g. a list
Sunday, January 25, 15
9
(defn map
([f]
(fn [rf]
(fn
([] (rf))
([result] (rf result))
([result input]
(rf result (f input)))
([result input & inputs]
(rf result (apply f input inputs))))))
Sunday, January 25, 15
10
(defn map ;; The tranducer factory...
([f] ;; ...accepts a single argument 'f', the transforming function
(fn [rf] ;; The transducer function accepts a reducing function 'rf'
(fn ;; This is the reducing function returned by the transducer
([] (rf)) ;; 0-arity : Forward to the zero-arity reducing function 'rf'
([result] (rf result)) ;; 1-arity : Forward to the one-arity reducing function 'rf'
([result input] ;; 2-arity : Perform the reduction with one arg to 'f'
(rf result (f input)))
([result input & inputs] ;; n-arity : Perform the reduction with multiple args to 'f'
(rf result (apply f input inputs))))))
Sunday, January 25, 15
11
(defn map ;; The tranducer factory...
([f] ;; ...accepts a single argument 'f', the transforming function
(fn [rf] ;; The transducer function accepts a reducing function 'rf'
(fn ;; This is the reducing function returned by the transducer
([] (rf)) ;; 0-arity : Return a 'seed' value obtained from 'rf'
([result] (rf result)) ;; 1-arity : Obtain final result from 'rf' and clean-up
([result input] ;; 2-arity : Perform the reduction with one arg to 'f'
(rf result (f input)))
([result input & inputs] ;; n-arity : Perform the reduction with multiple args to 'f'
(rf result (apply f input inputs))))))
Sunday, January 25, 15
12
(defn map ;; The tranducer factory...
([f] ;; ...accepts a single argument 'f', the transforming function
(fn [rf] ;; The transducer function accepts a reducing function 'rf'
(fn ;; This is the reducing function returned by the transducer
([] (rf)) ;; 0-arity : Return a 'seed' value obtained from 'rf'
([result] (rf result)) ;; 1-arity : Obtain final result from 'rf' and clean-up
([result input] ;; 2-arity : Perform the reduction with one arg to 'f'
(rf result (f input)))
([result input & inputs] ;; n-arity : Perform the reduction with multiple args to 'f'
(rf result (apply f input inputs))))))
To fully implement Clojure’s transducers in Python we also need:
‣ explicit association of the seed value with the reduction operation
‣ support for early termination without reducing the whole series
‣ reduction to a final value and opportunity to clean up state
Sunday, January 25, 15
13
class Reducer:
def __init__(self, reducer): # Construct from reducing function
pass
def initial(self): # Return the initial seed value
pass # 0-arity
def step(self, result, item): # Next step in the reduction
pass # 2-arity
def complete(self, result): # Produce a final result and clean up
pass # 1-arity
Sunday, January 25, 15
13
class Reducer:
def __init__(self, reducer): # Construct from reducing function
pass
def initial(self): # Return the initial seed value
pass # 0-arity
def step(self, result, item): # Next step in the reduction
pass # 2-arity
def complete(self, result): # Produce a final result and clean up
pass # 1-arity
new_reducer = Reducer(reducer)
Sunday, January 25, 15
13
class Reducer:
def __init__(self, reducer): # Construct from reducing function
pass
def initial(self): # Return the initial seed value
pass # 0-arity
def step(self, result, item): # Next step in the reduction
pass # 2-arity
def complete(self, result): # Produce a final result and clean up
pass # 1-arity
new_reducer = Reducer(reducer)
def transducer(reducer):
return Reducer(reducer)
Sunday, January 25, 15
13
class Reducer:
def __init__(self, reducer): # Construct from reducing function
pass
def initial(self): # Return the initial seed value
pass # 0-arity
def step(self, result, item): # Next step in the reduction
pass # 2-arity
def complete(self, result): # Produce a final result and clean up
pass # 1-arity
new_reducer = Reducer(reducer)
def transducer(reducer):
return Reducer(reducer)
⇐ two names for two concepts
Sunday, January 25, 15
Python Transducer implementations
14
Cognitect
https://github.com/cognitect-labs
PyPI: transducers
• “official”
• Python in the style of Clojure
• Only eager iterables (step back from
regular Python)
• Undesirable Python practices such as
hiding built-ins
• Also Clojure, Javascript, Ruby, etc.
Sixty North
http://code.sixty-north.com/python-
transducers
PyPI: transducer
• Pythonic
• Eager iterables
• Lazy iterables
• Co-routine based ‘push’ events
• Pull-requests welcome!
Sunday, January 25, 15
15
Thank you!
@sixty_north
Austin Bingham
@austin_bingham
http://sixty-north.com/blog/
Sunday, January 25, 15

Contenu connexe

Tendances

Demystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash SafetyDemystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash SafetyJean-François Gagné
 
JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0Mydbops
 
Obscure Go Optimisations
Obscure Go OptimisationsObscure Go Optimisations
Obscure Go OptimisationsBryan Boreham
 
SQL大量発行処理をいかにして高速化するか
SQL大量発行処理をいかにして高速化するかSQL大量発行処理をいかにして高速化するか
SQL大量発行処理をいかにして高速化するかShogo Wakayama
 
MySQLで論理削除と正しく付き合う方法
MySQLで論理削除と正しく付き合う方法MySQLで論理削除と正しく付き合う方法
MySQLで論理削除と正しく付き合う方法yoku0825
 
Optcarrot: A Pure-Ruby NES Emulator
Optcarrot: A Pure-Ruby NES EmulatorOptcarrot: A Pure-Ruby NES Emulator
Optcarrot: A Pure-Ruby NES Emulatormametter
 
Análise de Algoritmos - Análise Assintótica
Análise de Algoritmos - Análise AssintóticaAnálise de Algoritmos - Análise Assintótica
Análise de Algoritmos - Análise AssintóticaDelacyr Ferreira
 
Errant GTIDs breaking replication @ Percona Live 2019
Errant GTIDs breaking replication @ Percona Live 2019Errant GTIDs breaking replication @ Percona Live 2019
Errant GTIDs breaking replication @ Percona Live 2019Dieter Adriaenssens
 
Nippondanji氏に怒られても仕方ない、配列型とJSON型の使い方
Nippondanji氏に怒られても仕方ない、配列型とJSON型の使い方Nippondanji氏に怒られても仕方ない、配列型とJSON型の使い方
Nippondanji氏に怒られても仕方ない、配列型とJSON型の使い方kwatch
 
MySQL Casual Talks Vol.4 「MySQL-5.6で始める全文検索 〜InnoDB FTS編〜」
MySQL Casual Talks Vol.4 「MySQL-5.6で始める全文検索 〜InnoDB FTS編〜」MySQL Casual Talks Vol.4 「MySQL-5.6で始める全文検索 〜InnoDB FTS編〜」
MySQL Casual Talks Vol.4 「MySQL-5.6で始める全文検索 〜InnoDB FTS編〜」Kentaro Yoshida
 
C34 Always On 可用性グループ 構築時のポイント by 小澤真之
C34 Always On 可用性グループ 構築時のポイント by 小澤真之C34 Always On 可用性グループ 構築時のポイント by 小澤真之
C34 Always On 可用性グループ 構築時のポイント by 小澤真之Insight Technology, Inc.
 
Standard Edition 2でも使えるOracle Database 12c Release 2オススメ新機能
Standard Edition 2でも使えるOracle Database 12c Release 2オススメ新機能Standard Edition 2でも使えるOracle Database 12c Release 2オススメ新機能
Standard Edition 2でも使えるOracle Database 12c Release 2オススメ新機能Ryota Watabe
 
Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Mydbops
 
暗黒美夢王とEmacs
暗黒美夢王とEmacs暗黒美夢王とEmacs
暗黒美夢王とEmacsShougo
 
Sous-Interrogations - sql oracle
Sous-Interrogations - sql oracleSous-Interrogations - sql oracle
Sous-Interrogations - sql oraclewebreaker
 
Replication Troubleshooting in Classic VS GTID
Replication Troubleshooting in Classic VS GTIDReplication Troubleshooting in Classic VS GTID
Replication Troubleshooting in Classic VS GTIDMydbops
 
Azure AD DSドメインに仮想マシンを参加させる (トレノケ雲の会 mod1)
Azure AD DSドメインに仮想マシンを参加させる (トレノケ雲の会 mod1)Azure AD DSドメインに仮想マシンを参加させる (トレノケ雲の会 mod1)
Azure AD DSドメインに仮想マシンを参加させる (トレノケ雲の会 mod1)Trainocate Japan, Ltd.
 
ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)Mydbops
 
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZEMySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZENorvald Ryeng
 

Tendances (20)

Demystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash SafetyDemystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash Safety
 
JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0
 
Obscure Go Optimisations
Obscure Go OptimisationsObscure Go Optimisations
Obscure Go Optimisations
 
SQL大量発行処理をいかにして高速化するか
SQL大量発行処理をいかにして高速化するかSQL大量発行処理をいかにして高速化するか
SQL大量発行処理をいかにして高速化するか
 
MySQLで論理削除と正しく付き合う方法
MySQLで論理削除と正しく付き合う方法MySQLで論理削除と正しく付き合う方法
MySQLで論理削除と正しく付き合う方法
 
Optcarrot: A Pure-Ruby NES Emulator
Optcarrot: A Pure-Ruby NES EmulatorOptcarrot: A Pure-Ruby NES Emulator
Optcarrot: A Pure-Ruby NES Emulator
 
Análise de Algoritmos - Análise Assintótica
Análise de Algoritmos - Análise AssintóticaAnálise de Algoritmos - Análise Assintótica
Análise de Algoritmos - Análise Assintótica
 
Errant GTIDs breaking replication @ Percona Live 2019
Errant GTIDs breaking replication @ Percona Live 2019Errant GTIDs breaking replication @ Percona Live 2019
Errant GTIDs breaking replication @ Percona Live 2019
 
Nippondanji氏に怒られても仕方ない、配列型とJSON型の使い方
Nippondanji氏に怒られても仕方ない、配列型とJSON型の使い方Nippondanji氏に怒られても仕方ない、配列型とJSON型の使い方
Nippondanji氏に怒られても仕方ない、配列型とJSON型の使い方
 
MySQL Casual Talks Vol.4 「MySQL-5.6で始める全文検索 〜InnoDB FTS編〜」
MySQL Casual Talks Vol.4 「MySQL-5.6で始める全文検索 〜InnoDB FTS編〜」MySQL Casual Talks Vol.4 「MySQL-5.6で始める全文検索 〜InnoDB FTS編〜」
MySQL Casual Talks Vol.4 「MySQL-5.6で始める全文検索 〜InnoDB FTS編〜」
 
C34 Always On 可用性グループ 構築時のポイント by 小澤真之
C34 Always On 可用性グループ 構築時のポイント by 小澤真之C34 Always On 可用性グループ 構築時のポイント by 小澤真之
C34 Always On 可用性グループ 構築時のポイント by 小澤真之
 
Standard Edition 2でも使えるOracle Database 12c Release 2オススメ新機能
Standard Edition 2でも使えるOracle Database 12c Release 2オススメ新機能Standard Edition 2でも使えるOracle Database 12c Release 2オススメ新機能
Standard Edition 2でも使えるOracle Database 12c Release 2オススメ新機能
 
Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0
 
暗黒美夢王とEmacs
暗黒美夢王とEmacs暗黒美夢王とEmacs
暗黒美夢王とEmacs
 
Ad設計
Ad設計Ad設計
Ad設計
 
Sous-Interrogations - sql oracle
Sous-Interrogations - sql oracleSous-Interrogations - sql oracle
Sous-Interrogations - sql oracle
 
Replication Troubleshooting in Classic VS GTID
Replication Troubleshooting in Classic VS GTIDReplication Troubleshooting in Classic VS GTID
Replication Troubleshooting in Classic VS GTID
 
Azure AD DSドメインに仮想マシンを参加させる (トレノケ雲の会 mod1)
Azure AD DSドメインに仮想マシンを参加させる (トレノケ雲の会 mod1)Azure AD DSドメインに仮想マシンを参加させる (トレノケ雲の会 mod1)
Azure AD DSドメインに仮想マシンを参加させる (トレノケ雲の会 mod1)
 
ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)
 
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZEMySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
 

Similaire à Austin Bingham. Transducers in Python. PyCon Belarus

08-Iterators-and-Generators.pptx
08-Iterators-and-Generators.pptx08-Iterators-and-Generators.pptx
08-Iterators-and-Generators.pptxcursdjango
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Dhaval Dalal
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartChen Fisher
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingFrancesco Bruni
 
python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptxMONAR11
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monadsrkaippully
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patternsTomasz Kowal
 
The Challenge of Bringing FEZ to PlayStation Platforms
The Challenge of Bringing FEZ to PlayStation PlatformsThe Challenge of Bringing FEZ to PlayStation Platforms
The Challenge of Bringing FEZ to PlayStation PlatformsMiguel Angel Horna
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Samuel Fortier-Galarneau
 
Functional programming principles
Functional programming principlesFunctional programming principles
Functional programming principlesAndrew Denisov
 
Mapfilterreducepresentation
MapfilterreducepresentationMapfilterreducepresentation
MapfilterreducepresentationManjuKumara GH
 
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologiesit-people
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicGraham Dumpleton
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicNew Relic
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For BeginnersMatt Passell
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 

Similaire à Austin Bingham. Transducers in Python. PyCon Belarus (20)

08-Iterators-and-Generators.pptx
08-Iterators-and-Generators.pptx08-Iterators-and-Generators.pptx
08-Iterators-and-Generators.pptx
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptx
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
 
The Challenge of Bringing FEZ to PlayStation Platforms
The Challenge of Bringing FEZ to PlayStation PlatformsThe Challenge of Bringing FEZ to PlayStation Platforms
The Challenge of Bringing FEZ to PlayStation Platforms
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
 
Functional programming principles
Functional programming principlesFunctional programming principles
Functional programming principles
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Function & Recursion
Function & RecursionFunction & Recursion
Function & Recursion
 
Mapfilterreducepresentation
MapfilterreducepresentationMapfilterreducepresentation
Mapfilterreducepresentation
 
Gevent be or not to be
Gevent be or not to beGevent be or not to be
Gevent be or not to be
 
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 
Node js
Node jsNode js
Node js
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 

Plus de Alina Dolgikh

Reactive streams. Slava Schmidt
Reactive streams. Slava SchmidtReactive streams. Slava Schmidt
Reactive streams. Slava SchmidtAlina Dolgikh
 
Scala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаScala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаAlina Dolgikh
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникAlina Dolgikh
 
No sql unsuccessful_story. Владимир Зеленкевич
No sql unsuccessful_story. Владимир ЗеленкевичNo sql unsuccessful_story. Владимир Зеленкевич
No sql unsuccessful_story. Владимир ЗеленкевичAlina Dolgikh
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Appium + selenide comaqa.by. Антон Семенченко
Appium + selenide comaqa.by. Антон СеменченкоAppium + selenide comaqa.by. Антон Семенченко
Appium + selenide comaqa.by. Антон СеменченкоAlina Dolgikh
 
Cracking android app. Мокиенко Сергей
Cracking android app. Мокиенко СергейCracking android app. Мокиенко Сергей
Cracking android app. Мокиенко СергейAlina Dolgikh
 
David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015Alina Dolgikh
 
Владимир Еремин. Extending Openstack. PyCon Belarus 2015
Владимир Еремин. Extending Openstack. PyCon Belarus 2015Владимир Еремин. Extending Openstack. PyCon Belarus 2015
Владимир Еремин. Extending Openstack. PyCon Belarus 2015Alina Dolgikh
 
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015Alina Dolgikh
 
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...Alina Dolgikh
 
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...Alina Dolgikh
 
Austin Bingham. Python Refactoring. PyCon Belarus
Austin Bingham. Python Refactoring. PyCon BelarusAustin Bingham. Python Refactoring. PyCon Belarus
Austin Bingham. Python Refactoring. PyCon BelarusAlina Dolgikh
 
Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.Alina Dolgikh
 
Максим Лапшин. Erlang production
Максим Лапшин. Erlang productionМаксим Лапшин. Erlang production
Максим Лапшин. Erlang productionAlina Dolgikh
 
Максим Харченко. Erlang lincx
Максим Харченко. Erlang lincxМаксим Харченко. Erlang lincx
Максим Харченко. Erlang lincxAlina Dolgikh
 
Пиар в стартапе: извлекаем максимум пользы. Алексей Лартей
Пиар в стартапе: извлекаем максимум пользы. Алексей ЛартейПиар в стартапе: извлекаем максимум пользы. Алексей Лартей
Пиар в стартапе: извлекаем максимум пользы. Алексей ЛартейAlina Dolgikh
 
Подготовка проекта к первому раунду инвестиций. Дмитрий Поляков
Подготовка проекта к первому раунду инвестиций. Дмитрий ПоляковПодготовка проекта к первому раунду инвестиций. Дмитрий Поляков
Подготовка проекта к первому раунду инвестиций. Дмитрий ПоляковAlina Dolgikh
 
Как составлять правильный тизер для инвесторов? Никита Рогозин
Как составлять правильный тизер для инвесторов? Никита РогозинКак составлять правильный тизер для инвесторов? Никита Рогозин
Как составлять правильный тизер для инвесторов? Никита РогозинAlina Dolgikh
 
Startup belarus pres_khamiankova
Startup belarus pres_khamiankovaStartup belarus pres_khamiankova
Startup belarus pres_khamiankovaAlina Dolgikh
 

Plus de Alina Dolgikh (20)

Reactive streams. Slava Schmidt
Reactive streams. Slava SchmidtReactive streams. Slava Schmidt
Reactive streams. Slava Schmidt
 
Scala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаScala for the doubters. Максим Клыга
Scala for the doubters. Максим Клыга
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел Вейник
 
No sql unsuccessful_story. Владимир Зеленкевич
No sql unsuccessful_story. Владимир ЗеленкевичNo sql unsuccessful_story. Владимир Зеленкевич
No sql unsuccessful_story. Владимир Зеленкевич
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Appium + selenide comaqa.by. Антон Семенченко
Appium + selenide comaqa.by. Антон СеменченкоAppium + selenide comaqa.by. Антон Семенченко
Appium + selenide comaqa.by. Антон Семенченко
 
Cracking android app. Мокиенко Сергей
Cracking android app. Мокиенко СергейCracking android app. Мокиенко Сергей
Cracking android app. Мокиенко Сергей
 
David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015
 
Владимир Еремин. Extending Openstack. PyCon Belarus 2015
Владимир Еремин. Extending Openstack. PyCon Belarus 2015Владимир Еремин. Extending Openstack. PyCon Belarus 2015
Владимир Еремин. Extending Openstack. PyCon Belarus 2015
 
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015
 
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...
 
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...
 
Austin Bingham. Python Refactoring. PyCon Belarus
Austin Bingham. Python Refactoring. PyCon BelarusAustin Bingham. Python Refactoring. PyCon Belarus
Austin Bingham. Python Refactoring. PyCon Belarus
 
Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.
 
Максим Лапшин. Erlang production
Максим Лапшин. Erlang productionМаксим Лапшин. Erlang production
Максим Лапшин. Erlang production
 
Максим Харченко. Erlang lincx
Максим Харченко. Erlang lincxМаксим Харченко. Erlang lincx
Максим Харченко. Erlang lincx
 
Пиар в стартапе: извлекаем максимум пользы. Алексей Лартей
Пиар в стартапе: извлекаем максимум пользы. Алексей ЛартейПиар в стартапе: извлекаем максимум пользы. Алексей Лартей
Пиар в стартапе: извлекаем максимум пользы. Алексей Лартей
 
Подготовка проекта к первому раунду инвестиций. Дмитрий Поляков
Подготовка проекта к первому раунду инвестиций. Дмитрий ПоляковПодготовка проекта к первому раунду инвестиций. Дмитрий Поляков
Подготовка проекта к первому раунду инвестиций. Дмитрий Поляков
 
Как составлять правильный тизер для инвесторов? Никита Рогозин
Как составлять правильный тизер для инвесторов? Никита РогозинКак составлять правильный тизер для инвесторов? Никита Рогозин
Как составлять правильный тизер для инвесторов? Никита Рогозин
 
Startup belarus pres_khamiankova
Startup belarus pres_khamiankovaStartup belarus pres_khamiankova
Startup belarus pres_khamiankova
 

Dernier

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Dernier (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Austin Bingham. Transducers in Python. PyCon Belarus

  • 1. @sixty_north Understanding Transducers Through Python 1 Austin Bingham @austin_bingham Sunday, January 25, 15
  • 2. 237 “Transducers are coming” Rich Hickeyhttp://blog.cognitect.com/blog/2014/8/6/transducers-are-coming Photo: Howard Lewis Ship under CC-BY Sunday, January 25, 15
  • 3. Functions which transform reducers What is a transducer? ‣ Reducer (reducing function) • Any function we can pass to reduce(reducer, iterable[, initial]) • (result, input) → result • add(result, input) reduce(add, [1, 2, 3], 0) → 6 ‣ Transducer (transform reducer) • A function which accepts a reducer, and transforms it in some way, and returns a new reducer • ((result, input) → result) → ((result, input) → result) 3 Sunday, January 25, 15
  • 4. Transducers are a functional programming technique not restricted to Clojure How does this relate to Python? ‣ Clojure implementation is the prototype/archetype • Heavily uses anonymous functions • Uses overloads on function arity for disparate purposes • Complected with existing approaches ‣ Python implementation is pedagogical (but also useful) • Explicit is better than implicit • Readability counts! • Has all the functional tools we need for transducers • I’m a better Pythonista than Clojurist 4 Sunday, January 25, 15
  • 6. 6 my_filter(is_prime, my_map(prime_factors, range(32) ) ) iterable sequence sequence Sunday, January 25, 15
  • 7. 7 def my_map(transform, iterable): def map_reducer(sequence, item): sequence.append(transform(item)) return sequence return reduce(map_reducer, iterable, []) def my_filter(predicate, iterable): def filter_reducer(sequence, item): if predicate(item): sequence.append(item) return sequence return reduce(filter_reducer, iterable, []) Sunday, January 25, 15
  • 8. 7 def my_map(transform, iterable): def map_reducer(sequence, item): sequence.append(transform(item)) return sequence return reduce(map_reducer, iterable, []) def my_filter(predicate, iterable): def filter_reducer(sequence, item): if predicate(item): sequence.append(item) return sequence return reduce(filter_reducer, iterable, []) reduce() Sunday, January 25, 15
  • 9. 7 def my_map(transform, iterable): def map_reducer(sequence, item): sequence.append(transform(item)) return sequence return reduce(map_reducer, iterable, []) def my_filter(predicate, iterable): def filter_reducer(sequence, item): if predicate(item): sequence.append(item) return sequence return reduce(filter_reducer, iterable, []) reduce() sequence.append() Sunday, January 25, 15
  • 10. 7 def my_map(transform, iterable): def map_reducer(sequence, item): sequence.append(transform(item)) return sequence return reduce(map_reducer, iterable, []) def my_filter(predicate, iterable): def filter_reducer(sequence, item): if predicate(item): sequence.append(item) return sequence return reduce(filter_reducer, iterable, []) reduce() sequence.append() Empty list : ‘seed’ must be a mutable sequence Sunday, January 25, 15
  • 11. 8 >>> reduce(make_mapper(square), range(10), []) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> reduce(make_filterer(is_prime), range(100), []) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] ‣ make_mapper() and make_filterer() are not composable ‣ to square primes we would need to call reduce() twice ‣ this requires we store the intermediate sequence ‣ the reducers returned by make_mapper() and make_filterer() depend on the seed being a mutable sequence e.g. a list Sunday, January 25, 15
  • 12. 9 (defn map ([f] (fn [rf] (fn ([] (rf)) ([result] (rf result)) ([result input] (rf result (f input))) ([result input & inputs] (rf result (apply f input inputs)))))) Sunday, January 25, 15
  • 13. 10 (defn map ;; The tranducer factory... ([f] ;; ...accepts a single argument 'f', the transforming function (fn [rf] ;; The transducer function accepts a reducing function 'rf' (fn ;; This is the reducing function returned by the transducer ([] (rf)) ;; 0-arity : Forward to the zero-arity reducing function 'rf' ([result] (rf result)) ;; 1-arity : Forward to the one-arity reducing function 'rf' ([result input] ;; 2-arity : Perform the reduction with one arg to 'f' (rf result (f input))) ([result input & inputs] ;; n-arity : Perform the reduction with multiple args to 'f' (rf result (apply f input inputs)))))) Sunday, January 25, 15
  • 14. 11 (defn map ;; The tranducer factory... ([f] ;; ...accepts a single argument 'f', the transforming function (fn [rf] ;; The transducer function accepts a reducing function 'rf' (fn ;; This is the reducing function returned by the transducer ([] (rf)) ;; 0-arity : Return a 'seed' value obtained from 'rf' ([result] (rf result)) ;; 1-arity : Obtain final result from 'rf' and clean-up ([result input] ;; 2-arity : Perform the reduction with one arg to 'f' (rf result (f input))) ([result input & inputs] ;; n-arity : Perform the reduction with multiple args to 'f' (rf result (apply f input inputs)))))) Sunday, January 25, 15
  • 15. 12 (defn map ;; The tranducer factory... ([f] ;; ...accepts a single argument 'f', the transforming function (fn [rf] ;; The transducer function accepts a reducing function 'rf' (fn ;; This is the reducing function returned by the transducer ([] (rf)) ;; 0-arity : Return a 'seed' value obtained from 'rf' ([result] (rf result)) ;; 1-arity : Obtain final result from 'rf' and clean-up ([result input] ;; 2-arity : Perform the reduction with one arg to 'f' (rf result (f input))) ([result input & inputs] ;; n-arity : Perform the reduction with multiple args to 'f' (rf result (apply f input inputs)))))) To fully implement Clojure’s transducers in Python we also need: ‣ explicit association of the seed value with the reduction operation ‣ support for early termination without reducing the whole series ‣ reduction to a final value and opportunity to clean up state Sunday, January 25, 15
  • 16. 13 class Reducer: def __init__(self, reducer): # Construct from reducing function pass def initial(self): # Return the initial seed value pass # 0-arity def step(self, result, item): # Next step in the reduction pass # 2-arity def complete(self, result): # Produce a final result and clean up pass # 1-arity Sunday, January 25, 15
  • 17. 13 class Reducer: def __init__(self, reducer): # Construct from reducing function pass def initial(self): # Return the initial seed value pass # 0-arity def step(self, result, item): # Next step in the reduction pass # 2-arity def complete(self, result): # Produce a final result and clean up pass # 1-arity new_reducer = Reducer(reducer) Sunday, January 25, 15
  • 18. 13 class Reducer: def __init__(self, reducer): # Construct from reducing function pass def initial(self): # Return the initial seed value pass # 0-arity def step(self, result, item): # Next step in the reduction pass # 2-arity def complete(self, result): # Produce a final result and clean up pass # 1-arity new_reducer = Reducer(reducer) def transducer(reducer): return Reducer(reducer) Sunday, January 25, 15
  • 19. 13 class Reducer: def __init__(self, reducer): # Construct from reducing function pass def initial(self): # Return the initial seed value pass # 0-arity def step(self, result, item): # Next step in the reduction pass # 2-arity def complete(self, result): # Produce a final result and clean up pass # 1-arity new_reducer = Reducer(reducer) def transducer(reducer): return Reducer(reducer) ⇐ two names for two concepts Sunday, January 25, 15
  • 20. Python Transducer implementations 14 Cognitect https://github.com/cognitect-labs PyPI: transducers • “official” • Python in the style of Clojure • Only eager iterables (step back from regular Python) • Undesirable Python practices such as hiding built-ins • Also Clojure, Javascript, Ruby, etc. Sixty North http://code.sixty-north.com/python- transducers PyPI: transducer • Pythonic • Eager iterables • Lazy iterables • Co-routine based ‘push’ events • Pull-requests welcome! Sunday, January 25, 15