Skip to content

Instantly share code, notes, and snippets.

@tavisrudd
Last active May 23, 2017 14:30

Revisions

  1. tavisrudd renamed this gist May 30, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. tavisrudd revised this gist Aug 15, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion _
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    Lazy, infinite recursive sequences in bash (like in Haskell, if you squint).
    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.
  3. tavisrudd created this gist Aug 15, 2013.
    10 changes: 10 additions & 0 deletions _
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,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"
    2 changes: 2 additions & 0 deletions fibs.hs
    Original file line number Diff line number Diff line change
    @@ -0,0 +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
    16 changes: 16 additions & 0 deletions fibs_lazy.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,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
    7 changes: 7 additions & 0 deletions fibs_non_lazy.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,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