Bash fibonacci version spawns a lot of processes
First of all, I enjoyed reading the article. ("A Lisp REPL as my main shell", in case that "Comments" section is common for whole blog/site).
I made an observation, that it is unfair to compare pure math of lisp version to sub-shell spawning version in bash (if [ is also a new process).
All of the above just perfectly proves your point, that bash is cumbersome to use ;)
I'm attaching sane versions of recursive fibonacci, in bash (it pushes values on stack to stay in single shell), and also versions that call gawk or bc, which despite calling additional tool are a lot cleaner.
Pure bash version computes fib30 in under 3 minutes. Others compute fib33 in under 3 seconds.
#!/bin/bash
fibonacci () {
local ans prev1 prev2
# global: stack
if [[ $1 -lt 2 ]]; then
ans="$1"
else
fibonacci $(($1 - 1)) push
fibonacci $(($1 - 2)) push
prev1=${stack[$((${#stack[@]}-1))]}
unset stack[$((${#stack[@]}-1))]
prev2=${stack[$((${#stack[@]}-1))]}
unset stack[$((${#stack[@]}-1))]
ans=$((prev1+prev2))
fi
if [ -n "$2" ]; then
stack[${#stack[@]}]="$ans"
else
echo "$ans"
fi
}
fibo-awk() {
gawk -M -v q="$1" '
function fib(n) {
if (n < 2)
return n
return fib(n-1) + fib(n-2)
}
BEGIN {
print fib(q)
}
'
}
fibo-bc() {
bc <<<'
define fib(n) {
if (n < 2)
return n
return fib(n-1) + fib(n-2)
}
'"fib($1)"
}
#~ time fibonacci 30
time fibo-awk 33
time fibo-bc 33