dc
The Unix desk calculator, and the esoteric language that made it big.
Turing complete: yes · ●●○ moderate · esolangs.org
Tested with 2 known programs · Test method
Run it
The idea
dc was written in assembler for Unix V1 and moved to C for Version 7 Unix. There it got a wrapper, bc, that turned a desk calculator like the HP-48 into one for mere mortals. Through bc, dc was used on many Unix versions by people who never saw it.
Read the story
Numbers are decimals of any size, with as many places after the point as the scale register asks for. A string in brackets is a program too, and x runs it. There are no loops; a macro that runs itself again is the loop. The registers are stacks of their own, and each one can hold an array.
The machine
| Command | Does |
|---|---|
12.5 _3 | Push a number; _ is the minus |
[...] | Push a string |
+ - * / % ^ v | Arithmetic and square root, to k places |
p n P f | Print the top, pop and print, print as bytes, print all |
c d r z | Clear, duplicate, swap, push the depth |
sX lX SX LX | Store, load, push to and pop from register X |
:X ;X | Set and read an element of the array in X |
x | Run the string on top |
<X >X =X | Pop two and run X if the top is less, greater, equal |
q Q | Leave two macro levels; leave as many as popped |
i o k | Set the input base, the output base, the scale |
? | Read a line of input and run it |
Registers and arrays work as the specification describes them. Elsewhere, where versions differ, this implementation follows GNU dc, and it has the BSD commands the specification lists too. Errors go to standard error in dc and leave the stack as it was, so they are not shown.
Example
Try It Online's Hello World prints a string.
Try It Online's Hello World prints a string.
The first 20 Fibonacci numbers keep the pair on the stack, and for a moment one of them in the scale register, with k and K. The loop runs while the next number has fewer than 5 digits.
The factorials, 1! to 20!, printed in base 11. Register a counts, and the macro in y runs itself again while 20 is greater than the count.
With a scale of 20 the square root of 2 keeps 20 places.
Patterns it teaches
- Stack machines: every command works on the main stack.
- Code as data: a macro is a string that can be stored, copied and run.
- Turing completeness: the specification gives five proofs, among them a translation of brainfuck into dc.
Further
See also
Stack-based
Write your own in Run Convert a program from dc
Implementation
JavaScript interpreter, source and command line
A JavaScript interpreter, used in the browser and on the command line. Id: dc.
Command line
shib run dc -e '1d[prdk+KdZ5>x]dsxx'shib manual dcSource
- Module
langs/wiki/ports.js- Interpreter
langs/wiki/dc.js
Docs: Kernel instructions · The .shib format · Command line · Adding a language
Source esolangs.org (CC0) · Edit on esolangs.org