Skip to content

Comment on (Python) Generator Tricks For Systems Programmer (pdf)

Comments

If you really like the "pipelined" approach to describing data processing, postfix languages sing at it. Factor (http://factorcode.org/) is well worth investigating.

edit: I built a little toy system for working with generators in Forth- some aspects are a bit messy, but you can still write code like

  100 upto sum dup * 100 upto { dup * } map sum -
(https://github.com/JohnEarnest/Mako/blob/master/examples/Alg...)

Apart from chaining generators, you can write a simple helper to pipe general expressions.

    def pipe(cur_val, *fns):
        """
        Pipes `cur_val` through `fns`.
        ::
            def sqr(x): return x * x

            def negate(x): return -x

        `pipe(5, sqr, negate)`

        is the same as
        ::
            negate(sqr(5))
        """
        for fn in fns:
            cur_val = fn(cur_val)
        return cur_val

I find `pipe(5, sqr, negate)` neater than `negate(sqr(5))`, especially when the nesting is greater than 2.

This is inspired by clojure's threading macro -> and a re-factoring of @fogus's code snippet on stack overflow. He used reduce to implement the loop - though loops can be implemented with reduce, and that's how you generally do it in clojure et al., it isn't idiomatic Python.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.