public
Created

Lazy, infinite recursive sequences in Bash (like in Haskell, if you squint). The result is ugly but interesting.

  • Download Gist
_
1 2 3 4 5 6 7 8 9 10
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"
fibs.hs
Haskell
1 2
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
-- see http://stackoverflow.com/questions/6273621/understanding-a-recursively-defined-list-fibs-in-terms-of-zipwith
fibs_lazy.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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
fibs_non_lazy.sh
Shell
1 2 3 4 5 6 7
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.