Few minutes ago I needed to solve trivial problem of getting all parent directories of file. It's very easy to do it imperatively, but it would simply not satisfy me. Hence, I challenged myself to do it declaratively in python.
The problem is simple, but let me put an example on the table, so it's even easier to imagine what are we talking about.
Given some path, e.g.
/home/szborows/code/the-best-project-in-the-world
You want to have following list of parents:
/home/szborows/code
/home/szborows
/home
/
It's trivial to do this using split and then some for loop. How to make it more declarative?
Thinking more mathematically we simply want to get all of the subsets from some ordered set S that form prefix w.r.t. S. So we can simply generate pairs of numbers (1, y) , where y belongs to [1, len S) . We can actually ignore this constant 1 and just operate on numbers. In Python, to generate numbers starting from len(path) and going down we can simply utilize range() and [::-1] (this reverses collections, it's an idiom). Then join() can be used on splited path, but with slicing from 1 to y. That's it. And now demonstration:>>> path = '/a/b/c/d'
>>> ['/' + '/'.join(path.split('/')[1:l]) for l in range(len(path.split('/')))[::-1] if l] ['/a/b/c', '/a/b', '/a', '/']