{"id":804,"date":"2009-09-08T15:21:11","date_gmt":"2009-09-08T15:21:11","guid":{"rendered":"http:\/\/scientopia.org\/blogs\/goodmath\/2009\/09\/08\/two-dimensional-pathology-befunge\/"},"modified":"2009-09-08T15:21:11","modified_gmt":"2009-09-08T15:21:11","slug":"two-dimensional-pathology-befunge","status":"publish","type":"post","link":"http:\/\/www.goodmath.org\/blog\/2009\/09\/08\/two-dimensional-pathology-befunge\/","title":{"rendered":"Two-Dimensional Pathology: Befunge"},"content":{"rendered":"<p><em>I&#8217;m currently away on a family vacation, and as soon as vacation is<br \/>\nover, I&#8217;m off on a business trip for a week. And along the way, I&#8217;ve got some<br \/>\ndeadlines for my book. So to fill in, I&#8217;m recycling some old posts. I decided<br \/>\nthat it&#8217;s been entirely too long since there was any pathological programming<br \/>\n&#8217;round these parts, so I&#8217;m going to repost some of my favorites.<\/em><\/p>\n<p> Today, we&#8217;re going to take a look at a brilliant language called <a href=\"http:\/\/catseye.mine.nu:8080\/projects\/befunge93\/\"><b>Befunge<\/b><\/a>.<br \/>\nBefunge is the work of an evil genius named Chris Pressey. <\/p>\n<p> Normal programming languages are based on a basically one-dimensional<br \/>\nsyntax; the program is a string, a sequence of characters, and it&#8217;s processed<br \/>\nby reading that string in a straight-ahead fashion. But that&#8217;s not Befunge!<br \/>\nIt&#8217;s got a two-dimensional syntax. Befunge is something like a two-dimensional<br \/>\nturing machine: the program is written on a two dimensional<em>torus<\/em> called the playfield. Each<br \/>\ninstruction in Befunge is a single character, and where it&#8217;s located on the<br \/>\ntorus is crucial &#8211; control is going to move either up\/down or left\/right<br \/>\non the torus. All of the control flow is expressed by just changing the direction that<br \/>\nthe head moves over the torus.<\/p>\n<p> (In case you&#8217;re not familiar with a torus, it&#8217;s what you get<br \/>\nif you take a very flexible sheet of paper, and roll it so that you connect<br \/>\nthe top edge to the bottom, and then roll that tube so that you connect the<br \/>\nleft edge to the right. You get a donut shape where moving up from what used<br \/>\nto be the top of the page puts you on the bottom of the page; moving left from<br \/>\nthe left edge of the page puts you on the right.) <\/p>\n<p><!--more--><\/p>\n<p> The basics of computation in Befunge are pretty straightforward. It&#8217;s a<br \/>\nstack based language. Operations take their parameters from the stack, and<br \/>\nleave their results on the stack. Nothing too complicated there. There are<br \/>\narithmetic operators, IO operators, control flow operators, all operating on<br \/>\nthe values on the stack. <\/p>\n<p> The arithmetic operators are the usual kinds of things: There are<br \/>\noperators for addition (+), subtraction (-), division (\/), multiplication (*),<br \/>\nmodulo (%), and logical negation (!). Digit characters are treated as<br \/>\noperators that push the numeric value of the digit onto the stack. (So &#8220;99&#8221;<br \/>\nwill create a stack with two nines.) Comparisons are done using &#8220;`&#8221;, which<br \/>\npops the top two values from the stack and compares them. So if the top of the<br \/>\nstack was &#8220;x&#8221;, and the value beneath it was &#8220;y&#8221;, then &#8220;`&#8221; would leave a &#8220;0&#8221; on<br \/>\nthe stack if x&le;y, and 1 if x &gt; y. <\/p>\n<p> For IO, there are four operators. &#8220;&amp;&#8221; reads an integer from standard input<br \/>\nand pushes it onto the stack. &#8220;~&#8221; reads a single character from standard<br \/>\ninput, and leaves it on the stack. &#8220;.&#8221; pops a value off the stack and writes<br \/>\nit to standard out as an integer. &#8220;,&#8221; pops a value off the stack and writes it<br \/>\nto standard out as a character. <\/p>\n<p> Of course, we can&#8217;t have a stack-based language without some stack<br \/>\noperators: &#8220;:&#8221; makes a duplicate of the top value on the stack; &#8220;$&#8221; discards<br \/>\nthe top value on the stack; &#8220;&#8221; swaps the top two values of the stack.<\/p>\n<\/p>\n<p> So far, nothing has looked particularly pathological &#8211; in fact, nothing<br \/>\neven looks particularly strange, other that the fact that it&#8217;s pretty<br \/>\nillegible because of the single-character operators. But now, we get to<br \/>\ncontrol flow, and <em>that<\/em> is where the insanity\/brilliance of Befunge<br \/>\nreveals itself. <\/p>\n<p> In Befunge, there&#8217;s a read-head that moves over the program. Each step, it<br \/>\nexecutes the instruction under the head. But instead of just moving left or<br \/>\nright, it can move left, right, up, or down. &#8220;&gt;&#8221; is an instruction that tells<br \/>\nthe head to start moving to the right; &#8220;&lt;&#8221; tells the head to start moving<br \/>\nleft; &#8220;^&#8221; means start moving up, and &#8220;v&#8221; means to start moving down. So, for<br \/>\nexample: <\/p>\n<pre>\n&gt;v\n^&lt;\n<\/pre>\n<p> Is a program that runs an infinite loop: the head will just cycle over<br \/>\nthose four characters. An even more interesting infinite loop (taken from the<br \/>\nbefunge documentation) is:<\/p>\n<pre>\n&gt;v&gt;v\n&gt;^\n^  &lt;\n<\/pre>\n<p> Conditionals work by picking the direction that the head will move: &#8220;_&#8221; pops the stack, and if the value is zero, then it makes the head move right (&#8220;&gt;&#8221;); if it&#8217;s non-zero, it makes the head move left (&#8220;&lt;&quot;). Similarly, &quot;|&quot; pops a value, and makes the head move up if the value was non-zero, or down if it was zero.  To make things confusing, &quot;#&quot; means &quot;skip the next instruction.&quot; (Actually, it&#039;s important for when a vertical and horizontal control flow cross.) And finally,<br \/>\n&quot;@&quot; is the exit command; it makes the head stop, and the program halt.\n<\/p>\n<p> There&#8217;s also a little hack for strings. A double-quote character (&#8220;)<br \/>\nstarts a string; when one is encountered, the head keeps moving in the same<br \/>\ndirection, but instead of executing the characters as instuctions, it just<br \/>\npushes the character values onto the stack. When the second quote is found, it<br \/>\ngoes back to executing instructions.<\/p>\n<p> Finally, just in case the basic two dimensional flow control isn&#8217;t<br \/>\npathological enough, there are two instructions for modifying cells on the<br \/>\nplayfield! &#8220;g&#8221; pops an X and Y value off the stack, and pushes the character<br \/>\nat (X,Y) onto the stack; &#8220;p&#8221; pops an X, Y, and a character off the stack, and<br \/>\nwrites the character onto location (X,Y) of the playfield. (The coordinates<br \/>\nare relative to the cell where the program started.)<\/p>\n<p> So, let&#8217;s look at a couple of befunge programs. As usual, we start with<br \/>\nthe good old &#8220;hello world&#8221;.<\/p>\n<pre>\nv\n&gt;v\"Hello world!\"0&lt;\n,:\n^_25*,@\n<\/pre>\n<p>We start at the top left, head moving right. It moves until it hits the &#8220;v&#8221;<br \/>\ncharacter, which makes it go down; then &#8220;&lt;&#8221; makes it go left. 0 pushes a zero<br \/>\nonto the stack. Then we&#8217;ve got a quote &#8211; so it starts pushing characters onto<br \/>\nthe stack until the next quote. When we get to the next quote, if we wrote the<br \/>\nstack so that the top comes first, it would look like : (&#8216;H&#8217; &#8216;e&#8217; &#8216;l&#8217; &#8216;l&#8217; &#8216;o&#8217; &#8216;<br \/>\n&#8216; &#8216;w&#8217; &#8216;o&#8217; &#8216;r&#8217; &#8216;l&#8217; &#8216;d&#8217; &#8216;!&#8217; 0 ).<\/p>\n<p> Then we hit a &#8220;v&#8221; which makes the head go down. This is the beginning of a<br \/>\nloop; the leftmost two characters of rows 2, 3, and 4 are a while loop! The<br \/>\nhead goes down to &#8220;:&#8221; which duplicates the top of the stack; then it hits &#8220;_&#8221;,<br \/>\nwhich turns left if the value on top of the stack is not zero; then the head<br \/>\nturns up, outputs a character, turns right, and we&#8217;re back at the start of the<br \/>\nloop. So the loop will output each character until we get the the &#8220;0&#8221; we<br \/>\npushed before the string; then at the &#8220;_&#8221;, we turn right. 2 and 5 are pushed<br \/>\non the stack and multiplied, leaving a 10, which is the linefeed character<br \/>\n(basically &#8220;n&#8221; for you C weenies). It outputs the linefeed, and then exits.\n<\/p>\n<p> How about a truly pathological example? Here&#8217;s a self-reproducing program<br \/>\nin 12 bytes.<\/p>\n<pre> :0g,:93+`#@_1+ <\/pre>\n<p>Stepping through that:<\/p>\n<ol>\n<li> Dup the value on top of the stack.<br \/>\nThat&#8217;ll produce a &#8220;0&#8221; if the stack is empty. (So first pass, stack=[0])<\/li>\n<li> &#8220;0&#8221; Push a zero on the stack. (First pass, stack=[0,0])<\/li>\n<li> &#8220;g&#8221;: Fetch the value at (x,y) on the stack; that&#8217;s (0,0) initially.<br \/>\n(First pass, stack = [&#8216;:&#8217;])<\/li>\n<li> &#8220;,&#8221;: Output it. So we printed the character at (0,0) (First pass, stack<br \/>\n= [])<\/li>\n<li> &#8220;:&#8221; dup the stack top again. (First pass, stack = [0])<\/li>\n<li> &#8220;93+&#8221;. Get the number 12 onto the stack. (First pass, stack = [12,0])<\/li>\n<li> Compare what was on top of the stack to twelve. Leave a 0 there if it<br \/>\nwas, or a 1 if it wasn&#8217;t. (First pass, stack = [0]).<\/li>\n<li> &#8220;#&#8221; skip over the next character.<\/li>\n<li> &#8220;_&#8221; go right if the top of stack is zero; left if it&#8217;s one. So if the<br \/>\nvalue copied by the second &#8220;:&#8221; was greater than 12, then go left (in which<br \/>\ncase you hit &#8220;@&#8221; and halt); otherwise, keep going right.<\/li>\n<li> &#8220;1+&#8221;: add one to the top of the stack (First pass, stack = ([1])). Then<br \/>\nkeep going right until you hit the right edge, and the you jump back to the<br \/>\nleft edge, so you&#8217;re at the first &#8220;:&#8221; again.<\/li>\n<li> Now the whole thing repeats, except that there&#8217;s a one on the stack. So<br \/>\nthe &#8220;g&#8221; will fetch (1,0); the &#8220;12&#8221; will be compared to 1, and the &#8220;1+&#8221; on the<br \/>\nend will leave &#8220;2&#8221; on the stack. So now it fetches and outputs (2,0). And so<br \/>\non, until it reaches the &#8220;(_)&#8221; after outputting (12,0), when it halts. <\/li>\n<\/ol>\n<p> One more, which I&#8217;ll let you figure out for yourself. Here&#8217;s a program<br \/>\nthat prompts you for a number, and computes its factorial:<\/p>\n<pre>\nv\n&gt;v\"Please enter a number (1-16) : \"0&lt;\n,:             &gt;$*99g1-:99p#v_.25*,@\n^_&amp;:1-99p&gt;:1-:!|10          &lt;\n^     &lt;\n<\/pre>\n<p> So is Befunge Turing complete? The answer is less obvious than many other programming<br \/>\nlanguages. In fact, it was a point of debate in the esolang community for a while.<br \/>\nThe ultimate answer is that <em>if<\/em> the stack can contain arbitrarily large<br \/>\nnumbers, then it&#8217;s Turing complete. Otherwise, you&#8217;re stuck in pushdown-automata<br \/>\nland. You&#8217;ve got unbounded storage on the stack, but you can only access<br \/>\nthe top two elements &#8211; so you&#8217;ve got no random-access storage. If you&#8217;ve<br \/>\ngot arbitrarily large numbers, you can put together a scheme for random-access<br \/>\nstorage using data encoded into those big numbers. Want proof?<\/p>\n<pre>\n&lt;v+**44_v        v88+*&lt;v:!-\".\":!-\",\":!-\"&gt;\":!-\"&lt;\":!-\"-\":!-\"+\":!-\"!\":~&lt;+8\n0&gt; :7`!^         &gt;4**-v*&gt;\"[\"-!\"]\"-!#v_  #v_  #v_  #v_  #v_  #v_  #v_  #v_!#^_\nv     $&lt;             #*             &gt;1+$&gt;1+$&gt;1+$&gt;1+$&gt;1+$&gt;1+$&gt;1+$&gt;   ^\n&gt;0:44*&gt;\/44*%:7`#v_:00p8+44**&gt;+:1`#v_$:888**\/888&gt;**%:884**`!#v_        v\n      ^ *44:_@#:&lt;    #^88$&lt; ^ **44&lt;                ^ 888\/**888:&lt;         0\n$00g1-:0`#v_1-:0`#v_1-:0`#^_1-:0`#v_1-:0`#v_1-:0`#v_1-0`#v_v            &gt;\nv_v        &gt;$1+v -1$&lt; $&gt;      v+**488$&lt;    v~<img src='http:\/\/l.wordpress.com\/latex.php?latex=%26lt%3B%20%20%20%20v%2C%3A%24%26lt%3B%20%20%20%20%20%20%20%20%20%20%20%20%26gt%3B%3A884%2A%2A%60%23%23%20%26lt%3B%20%20%20%20%20%20%20%20%20%20%20%20%26gt%3B884%2A%2A%25%20%20%20%20%20%20%20%26gt%3B%26gt%3B%20%20%20%20%20%20%20%20%20%20%20%20%26gt%3B%20%20%20%20%20%20%20%20%26gt%3B%20%20%20%20%20%26gt%3B888%2A%20%2A%20%2A%2B%5E%20%2B%2A%2A%2A888%24%3A0%3A44%2A%2F%26gt%3B44%2A%25%3A7%60%23v_44%2A%26gt%3B%2A%2B%3A1%60v%20%20%20%20%20%20%20%20%5E%20%20p80%2B%2A%2A562%26lt%3B0_%5E%23%21%3A%20%20%26lt%3B%20%3A%20%20%20%20%20%20%20%20%20%20%20%20v%5E%20%20%20%20%20%20%20%20%20%20%20%5E%20%2F%2A44%3A%26lt%3B%20%20%20%20%20%5E%2A44-8_%24%3A44%2A%26gt%3B%2F44%2A%25%3A7%60v%20%5E2_%5E%23%20%20%20%20%20%20%26lt%3B%20%20%20%20%20%20%20%20%20%20%20%20%24%60%23v_8%26gt%3B%2B1%60%23v_v%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5E%2A44%3A%20%20%20%20_&#038;bg=FFFFFF&#038;fg=000000&#038;s=0' title='&lt;    v,:$&lt;            &gt;:884**`## &lt;            &gt;884**%       &gt;&gt;            &gt;        &gt;     &gt;888* * *+^ +***888$:0:44*\/&gt;44*%:7`#v_44*&gt;*+:1`v        ^  p80+**562&lt;0_^#!:  &lt; :            v^           ^ \/*44:&lt;     ^*44-8_$:44*&gt;\/44*%:7`v ^2_^#      &lt;            $`#v_8&gt;+1`#v_v                            ^*44:    _' style='vertical-align:1%' class='tex' alt='&lt;    v,:$&lt;            &gt;:884**`## &lt;            &gt;884**%       &gt;&gt;            &gt;        &gt;     &gt;888* * *+^ +***888$:0:44*\/&gt;44*%:7`#v_44*&gt;*+:1`v        ^  p80+**562&lt;0_^#!:  &lt; :            v^           ^ \/*44:&lt;     ^*44-8_$:44*&gt;\/44*%:7`v ^2_^#      &lt;            $`#v_8&gt;+1`#v_v                            ^*44:    _' \/>$1:7&gt;6+`!#v_77+`#v_1-:0\n-1&lt;  ^8**44&lt; +                                              ^ 7:$&lt;1  &lt;+1&lt;\n^     0p80*84&lt;\n$:0:44*&gt;\/44*%:7`#v_44*&gt;*+:1`v                                            &gt;\n^ *44:    &lt;     ^*44-8_$:44*&gt;\/44*%:7`v\n#v_1-:#v_$\/8&gt;44*\/:0`#v_$&gt;`  #v_v       ^*44:    _44**+:1:4&gt;4*%:5`!#v_6`!\n&lt;   -1&lt;    ^  +8**44&lt;  ^+8**44&lt; +                             ^ 4:\/*44$&lt; 0+1\n^                         p80*84&lt;\n<\/pre>\n<p> That mess is a Brainfuck interpreter written in Befunge! And since<br \/>\nBrainfuck is Turing complete, so is Befunge with bignums. Unfortunately, the<br \/>\nsite from which I downloaded that was a geocities page that I can&#8217;t seem to access<br \/>\nanymore. (If you know who the author is, please let me know so that I can provide<br \/>\nattribution.)<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;m currently away on a family vacation, and as soon as vacation is over, I&#8217;m off on a business trip for a week. And along the way, I&#8217;ve got some deadlines for my book. So to fill in, I&#8217;m recycling some old posts. I decided that it&#8217;s been entirely too long since there was any [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[92],"tags":[],"class_list":["post-804","post","type-post","status-publish","format-standard","hentry","category-pathological-programming"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/p4lzZS-cY","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"_links":{"self":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts\/804","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/comments?post=804"}],"version-history":[{"count":0,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts\/804\/revisions"}],"wp:attachment":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/media?parent=804"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/categories?post=804"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/tags?post=804"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}