The function (output the power set of a given input)
p() { [ $# -eq 0 ] && echo || (shift; p "$@") |
while read r ; do echo -e "$1 $r\n$r"; done }
Test Input
p $(echo -e "1 2 3")
Test Output
1 2 3
2 3
1 3
3
1 2
2
1
I have difficulty grasping the recursion in the following code. I tried to understand it by placing some variables inside of the code to denote the level of recursion and the order of execution, but I am still puzzled.
Here are the things I can tell so far:
- The subshell's output will not be shown on the final output, as it gets redirected to the read command via pipe
- The
echocommand appends new line for all of its output
The order of execution I see is:
- p (1 2 3) -> 1 followed by all combination of output below\n all combination of output below
- p (2 3) -> 2 3\n3\n
- p (3) -> 3
- p () ->
So I think I should have p(2) instead of p(3) on execution #3, but how does that happen? Since shift only goes in one direction.
If I were to use "p(1 2 3 4)" as the input, it is the part that shows "1 2 3" in the output that confuses me.
$(echo -e "1\n2\n3")is equivalent to1 2 3. Perhaps it will be simpler to follow justp 1 2 3?