[Python-ideas] Elixir inspired pipe to apply a series of functions

Nick Coghlan ncoghlan at gmail.com
Sat Jun 15 06:20:35 CEST 2013


On 14 June 2013 04:06, Jan Wrobel <wrr at mixedbit.org> wrote:
> Hello,
>
> I've recently stumbled upon a Joe Armstrong's (of Erlang) blog post
> that praises an Elixir pipe operator:
>
> http://joearms.github.io/2013/05/31/a-week-with-elixir.html
>
> The operator allows to nicely structure code that applies a series of
> functions to transform an input value to some output.
>
> I often end up writing code like:
>
> pkcs7_unpad(
>   reduce(lambda result, block: result.append(block),
>     map(decrypt_block,
>       pairwise([iv] + secret_blocks))))
>
> Which is dense, and needs to be read backwards (last operation is
> written first), but as Joe notes, the alternative is also not very
> compelling:
>
>   decrypted_blocks = map(decrypt_block, pairwise([iv] + secret_blocks))
>   combined_blocks = reduce(lambda result, block: result.append(block))
>   return pkcs7_unpad(combined_blocks)

It's a whole lot clearer if you store some state on the heap instead
of insisting on using the stack:

    decrypted = []
    for block in itertools.chain([iv], secret_blocks):
       decrypted.append(decrypt_block(decrypted, block)
    return pkcs7_unpad(combined_blocks)

Inside every reduce call is a for loop trying to get out :P

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list