Skip to content

Instantly share code, notes, and snippets.

@tavisrudd
Last active May 23, 2017 14:30
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tavisrudd/6237770 to your computer and use it in GitHub Desktop.
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.
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
-- see http://stackoverflow.com/questions/6273621/understanding-a-recursively-defined-list-fibs-in-terms-of-zipwith
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
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
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"
@clrnd
Copy link

clrnd commented Aug 15, 2013

:|

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment