Fibonacci numbers (Sed)

From LiteratePrograms

Jump to: navigation, search
Other implementations: ALGOL 68 | Alice ML | bc | C | C Plus Plus templates | dc | E | Eiffel | Erlang | Forth | FORTRAN | Haskell | Hume | Icon | Java | JavaScript | Lisp | Logo | Lua | Mercury | OCaml | occam | Oz | Pascal | PIR | PostScript | Python | Ruby | Scala | Scheme | Sed | sh | sh, iterative | Smalltalk | T-SQL | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by

1 \\ \end{cases} ."/>

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.


Although 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:

s///
s/1/1/

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.

<<fibonacci.sed>>=
s/+//g

testing

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
Download code
Views