[Python-ideas] How do you think about these language extensions?

David Mertz mertz at gnosis.cx
Sat Aug 19 01:33:40 EDT 2017


This is pretty easy to write without any syntax changes, just using a
higher-order function `compose()` (possible implementation at foot).
Again, I'll assume auto-currying like the map/filter versions of those
functions in toolz, as Steven does:


> result = (myfile.readlines()
>           -> map(str.strip)
>           -> filter( lambda s: not s.startwith('#') )
>           -> sorted
>           -> collapse  # collapse runs of identical lines
>           -> extract_dates
>           -> map(date_to_seconds)
>           -> min
>           )
>

result = compose(map(str.strip),
                 filter(lambda s: not startswith('#'),
                 sorted,
                 collapse,
                 extract_dates,
                 map(date_to_seconds),
                 min
                 )(myfile.readlines())

Pretty much exactly the same thing with just a utility HOF.  There's one
that behaves right in `toolz`/`cytoolz`, or I've used this one in some
publications and teaching material:

def compose(*funcs):
    """Return a new function s.t.
       compose(f,g,...)(x) == f(g(...(x)))
    """
    def inner(data, funcs=funcs):
        result = data
        for f in reversed(funcs):
            result = f(result)
        return result
    return inner

-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170818/fbc1b88c/attachment-0001.html>


More information about the Python-ideas mailing list