Fibonacci numbers (Sed)
sed is capable of decimal arithmetic when pushed, the direct approach is to restrict ourselves to unary arithmetic, allowing straight transcription of the definition.
The first two cases might be transcribed as:
but as they are identities, we omit them, leaving the final case, which we first rewrite into the form
- F(n + 2) = F(n + 1) + F(n)
and then transcribe as:
<<fibonacci.sed>>= :F s/11\(1*\)/1\1+\1/ t F
The code above repeats until convergence, at which point F has been fully applied, but the resulting additions have yet to be evaluated. In unary, this is also straightforward: addition is concatenation.
To test, we sugar the output a little
<<fibonacci.sed>>= s/^/ = /
and ask for a few fibonacci numbers:
> sed -f fibonacci.sed 1 = 1 11 = 1 111 = 11 1111 = 111 11111 = 11111 111111 = 11111111 1111111 = 1111111111111 11111111 = 111111111111111111111
Unary rapidly becomes annoying for larger numbers, but a simple wrapper can provide decimal input and output.
> jot -b 1 -s "" 16 | sed -f fibonacci.sed | tr -Cd 1 | wc -c 987 > jot -b 1 -s "" 20 | sed -f fibonacci.sed | tr -Cd 1 | wc -c 6765