Last active
May 23, 2017 14:30
-
-
Save tavisrudd/6237770 to your computer and use it in GitHub Desktop.
Lazy, infinite recursive sequences in Bash (like in Haskell, if you squint). The result is ugly but interesting.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fibs = 0 : 1 : zipWith (+) fibs (tail fibs) | |
-- see http://stackoverflow.com/questions/6273621/understanding-a-recursively-defined-list-fibs-in-terms-of-zipwith |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
init() { mkfifo fib out; echo 0 1 1 >fib; } | |
gen_fibs () { | |
while read i j k; do | |
echo $j $k $(($j+$k)) | |
echo $i > out | |
done <fib>fib | |
} | |
read_results () { | |
while read res; do | |
echo $res | |
sleep .4 # otherwise it goes so fast the integers wrap before you can blink | |
done | |
} | |
init & | |
gen_fibs & | |
read_results < out |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mkfifo fib | |
echo 0 1 1 >fib & | |
while read i j k; do | |
echo $i >&2 | |
echo $j $k $(($j+$k)) | |
sleep .4 | |
done <fib >fib |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Lazy, infinite recursive sequences in Bash (like in Haskell, if you squint). | |
I was inspired by the beautiful Haskell zipWith implementation of the Fibonacci sequence `fibs = 0 : 1 : zipWith (+) fibs (tail fibs)` | |
to find an equivalent in bash using 'coroutines' and recursive pipes. | |
My original experiments were https://twitter.com/tavisrudd/status/367164339716751360 | |
"fun w/ recursive pipes: e=echo;mkfifo fib;{ $e 0 1 1 >fib &};{ while read i j k; do $e $i >&2; $e $j $k $(($j+$k));sleep .4; done;}<fib>fib" | |
and https://twitter.com/tavisrudd/status/367142071489937408 | |
"o=ouro;b=boros;mkfifo $o$b;e=echo; { $e $o > $o$b & }; { while read s;do $e $s>&2;case $s in $o)$e $b;;*)$e $o; esac; done; }<$o$b >$o$b" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:|