Hacker News new | ask | show | jobs
by pizza234 1283 days ago
It's important to separate this example from the general concept.

The concept is (generally) called functional composition.

The way one reasons about it, is to mentally split the statement at each function, and think about each step separately. The readability of functional composition comes from the fact there is interrelation exclusively between each adjancent couple of functions - in practice, the reader needs to keep only one result in mind at a time.

Functionally composed statements read like a sequence of statements, rather than a single one. The advantage is that they avoid having to use throwaway temporary variables for each step.

Shell pipes work the same. Even if they're long, assuming that they don't obscure features or use complex intermediate results, they're interpreted the same way - one transformation at a time.

Back to the example. It's not good for a few reasons:

1. it's not properly formatted

2. it uses an uncommon feature (named block variable, `_1`)

3. the sum at the end of the statement breaks the flow.

One would typically write the example like:

    index_found = File
        .read('input6.txt')
        .chars
        .each_cons(4)
        .find_index { |sequence| sequence.uniq == sequence }

    index_found + 4
Writing functional composition in Rust tends to be a bit cleaner, not because of the language, but because of the autoformatting, that indents the statement (but not the sum; that one, I've separated it manually).

Regarding debugging: you can split the statement as convenient, and recompose it once you're done with debugging. Depending on the given statement, one can also put breakpoints inside the blocks.