r/functionalprogramming • u/kinow mod • Apr 21 '25
Python Haskelling My Python
https://unnamed.website/posts/haskelling-my-python/
23
Upvotes
r/functionalprogramming • u/kinow mod • Apr 21 '25
View all comments
Show parent comment
3
u/11fdriver Apr 21 '25
You can
taketheints()function multiple times with no issue as the generator is recreated each time.But as generators are iterables that only permit a single pass, assigning
ints()to a var means that the mutable state persists through the calls.Python's duck-typing means that any iterable will do for the last arg; it could be a list, tuple, generator, etc, which handily means no extra work is needed to allow nested calls.
You can get around the downsides of recreating the generator each time by using memoization, as the post notes nicely. Note that although you could write
taketo acceptints(no parens) like a variable, it breaks nested calls totake:It all reminds me a bit of a Java pattern for reusable infinite Streams, which is to wrap them in a lambda. Java Streams get closed by terminal functions; it's an error to reuse them.