Images created with Timwi's tools with link provided in the Factoid!
The heaheaders Length n Snippet are Try It Online! links :)
These 2 are simplified (thus not a very good version) of a cat
program. For a real working one, please see here.
,;~
This reads and prints and also outputs a lot of trailing mysterious symbols. What's happening?
,
reads a byte and ;
prints it no matter what ,
gets (If there is no input, ,
will return a -1
and ;
will print it modulo 256 which is 255
).
Here is a trick which is useful in creating Hexagons: Using ~
(negation) to control the direction the IP goes before it reaches an if
(no matter it is an implicit one or an explicit one like <
and >
and some other conditionals).
If you find this hard to understand, then it's worth mentioning that this is not a linear loop. As an exercise imagine the above are put into a 2-hexagon and you'll see why we need ~
to do make a loop with the implicit if :P The code basically runs in the same manner as in the length 2 snippet below!
Thus, when there is a byte, the memory will be positive and ~
makes it negative so it goes back to the top to read another byte. Yet it won't stop...
So let's see the length 4 version of the cat
.
<,@;
When you try this, it looks good. Finally we have one program which stops!
It starts on the top left with an initial value of 0
. A trick here which is (again) quite common - deflect the initial IP with <
. This is particularly useful when the main loop should end when the calculated value is <=0
.
Here it comes to the blue path. ;
prints the null byte (as it is initially 0
) and ,
reads a byte. An implicit-if decides if it should go to the green one (doing nothing and wraps back to the main blue loop for printing this byte) or it should go to the red terminal @
.
In some code golf challenges, it is acceptable to have null bytes printed before the desired output. However this is not the case for the simple cat challenge attached above :P Also, this does not handle null bytes \0
well. If you are curious how to do the cat
with 6 bytes which handles \0
and prints nothing else and stops, check it out! (The 6 bytes solution is shown after the 7 bytes)