Implement a Truth-Machine

  • A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:




    • Gets a number (either 0 or 1) from STDIN.


    • If that number is 0, print out 0 and terminate.


    • If that number is 1, print out 1 forever.




    Challenge



    Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:




    • take input from STDIN or an acceptable alternative


      • If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program


    • must output to STDOUT or an acceptable alternative


      • If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.


    • when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

    • the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.


    • if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.




    Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).



    Catalog



    The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.



    To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:



    ## Language Name, N bytes


    where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:



    ## Ruby, <s>104</s> <s>101</s> 96 bytes


    If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:



    ## Perl, 43 + 2 (-p flag) = 45 bytes


    You can also make the language name a link which will then show up in the snippet:



    ## [><>](http://esolangs.org/wiki/Fish), 121 bytes




    <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 320px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 62732; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>




    Can we assume that the program halts when the processor finishes executing the written code, for a machine code entry?

    @ThomasKwa Yes.

    Assuming any behaviour is fine for all invalid inputs?

    @Cruncher Yes, the only inputs you should expect to get are 0 and 1.

    Is it alright if I just have single spaces between the `1`s?

    @El'endiaStarman Sure. I'll add that to the rules.

    Catalog is borked.

    Catalog appears to consider `Bf` and `bf` to be different languages.

    Without having looked at all of them, I suspect a significant number of entries here to be expecting inputs of "0\n" or "1\n". I expect this was expected by @quartata but it's not necessarily explicit in the challenge. Is there a standard definition of "input a number" somewhere on meta?

    100th upvote! :)

    Are non-zero exit codes ok? Also, can I forgo a space that would normally separate the `1`s? (i.e. `11 1 1 1 1 1 1 1`) I assume not for the second question.

    is exiting with an error allowed?

    @12Me21 This is allowed by default on all challenges.

    Is taking input as \x00 and \x01 over STDIN allowed?

    @CalculatorFeline "If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable."

    Well, my language does allow that, so :( RIP Newbiefuck, 4 bytes: `,[.]` I/O as \x00 and \x01

    While attempting this, I made a program that does just the opposite, when given zero it prints out infinite zeroes, and when given 1, does nothing

    Can the form of `1` change—is `1 1/1 1/1 1/1...` allowed?

    Is one allowed to print an infinite number of `1`s? That is, not print out `1`s forever, but print out an infinite list of `1`s all at once? This would be theoretically demonstrated, but the language has no notion of printing more than once. It just generates an output. So is it okay if it runs indefinitely, but would print infinite `1`s given infinite time (to finish executing)?

  • Hexagony, 6 bytes



    This was surprisingly tricky, and I'm not convinced it's optimal...



    <[email protected]!$?


    After padding and unfolding the code, this represents the following hex grid:



    enter image description here



    This uses a similar control flow like my recent error-free cat program, moving along anti-diagonals. To achieve that we start by deflecting the instruction pointer (IP) to the left, where the purple path wraps around to the lower left corner.



    ? reads the input as an integer. ! prints it back. . is just a no-op. Now the corner of the grid acts as a branch:



    If the input was 0, the IP will continue along the red path, which simply terminates the program with @.



    If the input was 1, the IP will continue on the green path. Again, . is just a no-op, but $ is the equivalent of Befunge's trampoline: it skips the next instruction. After wrapping, the next instruction would be the ?, but due to $ execution actually continues on the blue path, starting with ! to print another copy of the 1. This loop which only contains !..$ is now repeated indefinitely.



    A study of control flow in Hexagony...



    I believe the above solution is optimal. I've written a brute forcer, which checks all 6-byte Hexagony programs, which contain at least one each of [email protected] (which are necessary; I've also checked : and % in place of @ to terminate with a division-by-zero error, but that didn't help either). The check prints all the programs which a) produce a 0 on input 0 and terminate and b) produce at least two 1s (and nothing else) and don't terminate within the first 60 ticks of the program (200 ticks for 5-byte solutions). I doubt that any valid solution would take more than 200 ticks to correctly print the first 0 or the second 1 on such a small grid, so I don't think I've missed out on any potential solutions.



    The search didn't yield any results for 5 bytes, but 57 results for 6 bytes (using @; there's no need to terminate with an error if we can solve this cleanly in the same amount of bytes). Of those 57 only 6 were false positives which actually printed only two 1s and then entered an infinite loop without printing any more. One solution was listed twice because it contained two ! commands. That leaves exactly 50 valid solutions.



    There is a certain amount of degeneracy between the solutions where one or two characters are not substantial, e.g. because they're effectively no-ops anyway. The solutions can be grouped into 23 sets of genuinely distinct programs (in some cases, there is only a single character difference between two sets, but it changes the control flow substantially, so I've counted them separately). Two of the groups even make use of multiple instruction pointers in a very unexpected way. As I would never have come up with most of these ways to use the branches and mirrors, they make a very interesting study of what sorts of control flow are possible in Hexagony, and I have definitely learned some new tricks for future golfs.



    The overall control flow is almost always the same: read a number, print it. If it's 0 find a way to the @, if not keep looping through the ! while mainting an edge value of 1. There are four notable exceptions:




    • One solution (the one with two !) prints two 1s per iteration through the grid, therefore printing about twice as fast as the majority of programs. I've marked this one with x2 below.

    • A few solutions (those which contain an o) replace the 1 with a 111 (the character code of o), so they print three 1s per iteration, making them print about three times as fast as the majority of programs. I've marked these with x3 below.

    • Two solutions append a 1 to the edge value in each iteration (so 1 --> 11 --> 111 --> ...). Those print very fast, but they'll run out of memory eventually. I've marked these with OoM below.

    • Two solutions enter a very tight loop which merely bounces back and forth over the !, printing on every other tick (instead of of every 5th or so), which makes them slightly faster (and neater). I've marked these with >< below.



    So here is the entire zoo:



    #1                #5                #12                #19
    ?!/[email protected] ?$!>[email protected] .?!/[email protected] |!|[email protected] # ><
    ?!/[email protected] # OoM ?$!|[email protected] =?!/[email protected]
    ?!/[email protected] #20
    ?!/$\@ #6 #13 [email protected]?<!
    ?!/[email protected] # x3 ?/!<|@ .?/[email protected] [email protected]?<! # OoM
    ?!/[email protected] # x2 =?/[email protected] [email protected]=?<!
    #7 [email protected]?<! # x3
    #2 ?\!<|@ #14
    ?!>$)@ \[email protected] #21
    ?!>[email protected] #8 _>[email protected]
    ?!>[email protected] # x3 ?<!>[email protected] # >< #15
    ?!|$)@ \[email protected] #22
    ?!|[email protected] #9 <[email protected]$?
    ?!|[email protected] # x3 ?\[email protected]$ #16 <[email protected]/$?
    \[email protected] <[email protected]=$?
    #3 #10 <[email protected]!$?
    ?!|)[email protected] ?~#[email protected]) #17 <[email protected]!$?
    ?!|[email protected] ?~#[email protected] $$?\@! </@!$?
    ?!|[email protected] # x3 <[email protected]!$?
    #11 #18
    #4 ?$)\@! \$?\@! #23
    ?_!<@> ?$1\@! <<@]!?
    ?$o\@! # x3


    The following is a short walkthrough for a handful of the more representative groups. Especially groups 10 and 23 are worth checking out. There are many other interesting and sometimes convoluted paths in the other groups, but I think I've bored you enough at the end of this. For anyone who really wants to learn Hexagony, these are definitely worth investigating though, as they exhibit even more possible uses of the mirrors and $.



    Group 1



    This one isn't much more elaborate than my original solution, but the paths go in different directions. It also allows for the largest number of variations in a single cell, as the right-most no-op can be replaced with 5 different commands which still make this valid without changing the structure:



    enter image description here



    Group 2



    This one is quite interesting, because it only moves horizontally. After wrapping to the >, the IP reverses immediately, taking the branch in the corner. It's not entirely well visibly no the diagram, but in the case of the 1 we traverse the first row again, but backwards this time. This also means we run into ? again, which now returns 0 (EOF). This is fixed with ) (increment) to keep printing 1s. This also has 5 variations, as ) could also be 1 or o, and > could also be |:



    enter image description here



    Group 3



    This one looks almost identical to the previous one but it's messy as hell. Up to hitting | and then traversing the bottom or top row it's the same. But in the case of a loop, the $ now skips over the ) onto the mirror. So we follow the turquoise path to the right, now hit the increment, skip over the @ before we wrap around to the | again and then go back to the green path at the top.



    enter image description here



    Group 4



    I thought this one was particularly nifty:



    enter image description here



    The _ mirror in the top right corner is initially a no-op, so we print with ! and hit the <. The 0 path now hits the horizontal mirror and terminates. The 1 path takes a really interesting trajectory though: it deflects down, wraps to the !, gets redirected towards the horizontal and then wraps back to the ! again. It then keeps moving in this rhombus shape, printing twice per iteration (every third tick).



    Group 8



    This is one of the two solutions with a really tight printing loop:



    enter image description here



    The < acts as the branch. After wrapping twice, 0 hits @. 1 on the other hand, first skips the ?, then > sends it onto the the $ again, so that is skips the @. Then the IP wraps into the turquoise path, where it bounces back and forth between the > and < (wrapping around the edge in between).



    Group 10



    One of two groups which use other instruction pointers, and it's absolutely beautiful. Hexagony has 6 - each one starts from a different corner along the clockwise edge, but only one of them is active at a time.



    enter image description here



    As usual, we read with ?. Now ~ is unary negation: it turns the 1 into a -1. Next, we hit the #. This is one way to switch between IPs: it takes the current edge value modulo 6 and switches to the corresponding IP (IPs are numbered from 0 in the clockwise direction). So if the input was 0, then the IP simply remains the same, and travels boringly straight ahead into [email protected]. But if the input was 1, then the current value is -1 which is 5 (mod 6). So we switch to the IP which starts on the very same cell (the green path). Now # is a no-op and ? sets the memory edge to 0. ) increments so ! prints a 1. Now we hit ~ again to ensure that # is still a no-op (as opposed to switching us to IP 1 which would terminate the program). It's mindblowing how well everything fits together in this little program.



    Group 22



    Just to note, this is the group my original solution is in. It also happens to be largest group, because the no-op can be in two different places, and there are several choices for the actual (effective no-op) command.



    Group 23



    This is the other group using multiple IPs. In fact this one uses 3 different IPs. The top right corner is a bit of a mess, but I'll try to walk you through this:



    enter image description here



    So, the beginning you've seen before: < deflects North-East, ? reads input. Now ] is another way to change between IPs: it hands control to the next IP in clockwise order. So we switch control to the turquoise path which (I know it's hard to see) starts in the North-East corner going South-East. It is immediately reflected by the < so that it wraps to the South-East corner, going North-West. It also hits the ] so we switch to the next IP. This is the grey path starting in the East corner, going South-West. It prints the input, then wraps to the North-East corner. < deflects the path into the horizontal, where it is reflected by the other <. Now the right-hand < acts as a branch: if the input was 0, the IP moves North-East, and wraps to the @. If the input was 1, the IP moves to the !, wraps to the lef-thand < where it is reflected... now in the corner, it wraps back to the !, gets deflected by the the right <, reflected by the left < and the paths starts over...



    Quite a mess, but a beautiful mess. :)






    Diagrams generated with Timwi's amazing HexagonyColorer.


    whoa. just whoa.

    ^ agreed. So cool...

    .... wait what?

    @ThomasOltmann I admit this answer assumes some basic knowledge of the language. If you're actually interested in learning more about it, I've gone through the basics in this answer and in this answer, but I won't blame you if you're not. ;)

    This language is interesting... `{{{{{{` is a no-op.

    Yeah... the memory model looks a bit painful (but still better than a 1D tape, I guess)

    No! Nooo! The hexagons! They're in my dreams! Noooo!

  • Motorola MC14500B Machine Code, 2 bytes


    In hex:


    58EC

    Explanation:


    5  OR the register with input from the data bus
    8 Write the register to the data bus
    E Skip next instruction if register is zero
    C Jump

    The Motorola MC14500B is a 1-bit microcontroller; it has one 1-bit register and a 1-bit data bus. Since the opcodes are 4 bits each, there are only sixteen; half of them carry out a logical operation between the register and the bit on the data bus.


    The jump instruction sets a jump flag; when no address is provided, it is common to set the program counter to 0. If the input bit was zero, the processor will not jump. If the input bit was 1, the processor jumps back to the start; since we're ORing with input, it doesn't matter what the input signal is afterwards—the register will then be 1 forever.


    As is conventional, the register is initialized to 0.


    A list of the opcodes can be found on the data sheet, or here.


    2 bytes is definitely the minimum for this challenge.

    @CᴏɴᴏʀO'Bʀɪᴇɴ I've been looking for several hours through esolangs and lists of 4-bit processors to see if there's a 1 or 1.5, and haven't found one.

    Definitely the right tool for the job.

    Link is borked atm...

    @Mego he must have changed it... It was another site yesterday

    Are you sure that this works? I think this wouldn't halt even if the input is 0, according to the handbook. Refer to page 11 of the handbook: `The PC counts up sequentially in binary to its highest value and "wraps around" to zero and counts up again.`

    @petStorm That quote is an example of one possible configuration for the microcontroller. Another possible configuration could have it execute a finite program, which is what I was implicitly assuming. If it does wrap around, `58AB` would still work for 2 bytes by disabling the input and output pins after one output on input 0.

  • Arnold C, 296 Bytes



    IT'S SHOWTIME
    HEY CHRISTMAS TREE i
    YOU SET US UP @NO PROBLEMO
    BECAUSE I'M GOING TO SAY PLEASE i
    STICK AROUND i
    TALK TO THE HAND i
    CHILL
    BULLSHIT
    TALK TO THE HAND i
    YOU HAVE NO RESPECT FOR LOGIC
    YOU HAVE BEEN TERMINATED


    Not really competitive, but for the fun of it.
    Does not support stdin, replace @NO PROBLEMO with @I LIED for a zero value. @No Problemo is 1.



    Run with (assuming file is truthmachine.arnoldc):



    wget http://lhartikk.github.io/ArnoldC.jar
    java -jar ArnoldC.jar truthmachine.arnoldc
    java truthmachine

    Beautiful. I cried 10/10

    @ThomasKwa I think you have to use tabs for it to parse correctly. I haven't used this language in a while though, could be wrong.

    `BECAUSE I'M GOING TO SAY PLEASE` LOL

    It looks like this does `if(i){while(i) print(i);} else {print(i);}` Surely it would be shorter to do `print(i);while(i) print(i);`?

    Although `BULLSHIT` has a great contribution to the entertainment value of the program, technically it is unnecessary. You can factor the whole `BULLSHIT` branch out by moving `TALK TO THE HAND i` after `YOU HAVE NO RESPECT FOR LOGIC`.

    @GaborSch There is only one proper response to that: `BULLSHIT` ;)

    @user00001 `YOU HAVE NO RESPECT FOR LOGIC` :D

  • Minecraft, 18 Bytes (MC Version 15w45a)



    minecraft sketch



    As you can see, there is a lever directed into the repeating command block, which has the command say 1 in it. There is an signal inverting torch on top of that, which directs power into the single-run command block with the command say 0 in it.



    Whenever the switch is directed towards truthy, the repeater block uses the code say 1 to output infinite 1s. When the lever is redirected to false, it outputs a single 0.



    Note that this outputs a [@] by default. If you really want just straight up 1s and zeros, this becomes 34 bytes, where the code in the command blocks are tellraw @a [1] and tellraw @a [0]. This is using @Cᴏɴᴏʀ O'Bʀɪᴇɴ's suggested byte count for MC as can be found in Meta.


    You used a video game for code golf. +1

    @RK. This is actually fairly standard practice for simple challenges. There are at least two other users who use MC as a code golfing language - try the search bar with `is:answer Minecraft`. c:

    @FlagAsSpam lol nicely done. Also, thanks for that tip to search MC answers.

  • Bash + GNU utils, 13


    grep 0||yes 1



    Bash, 35


    read n;for((;n;));{ echo 1;};echo 0

    You know, I was wondering if a bash solution with yes would be possible...

    Nice! That's pretty clever

  • Ruby, 20



    print while/1/||gets


    Run from the command line to avoid warnings, as



    ruby -e "print while/1/||gets" <<< 0
    ruby -e "print while/1/||gets" <<< 1


    Explanation:



    Less golfed, this is



    while /1/ || gets
    print
    end


    When a Regexp is used in a conditional, it evaluates as falsey unless the variable $_ is populated and matches the pattern. On the first time through the loop, $_ is empty so we fall through to gets, which sets the value of $_ to a line read from STDIN. print with no arguments prints $_. Now we evaluate the conditional again. If we read in 1, we short-circuit and just print 1 again, and so on forever. Otherwise, we fall through to gets, but since there's no second line of input, gets returns nil, so the loop ends.


    It's nice when trivial tasks still allow mindblowing solutions even in "normal" languages. :)

    The `||gets` part is cool and all, but can't you just do `gets;print while/1/` and save a byte?

    No, then it doesn't print the 0 at all.

  • Microscript, 3 bytes


    i{p

    The shortest one I know.


    Explanation:


    i  Takes numeric input and puts it in register 1
    { while register 1 is truthy
    p Print the contents of register 1

    Microscript has implicit printing of register 1 upon termination, which is the reason why an input of 0 gets printed once.


    @quartata I matched you :D

    @CᴏɴᴏʀO'Bʀɪᴇɴ :O

    I'm seriously wondering if you wrote the question first, or the answer...

    The question. I just wanted to post this since it was the shortest one I came up with while writing the question. It is a catalog so there aren't any real winners.

  • Turing Machine Code, 32 22 bytes


    Using the rule table syntax found here.


    0 0 0 * halt
    0 * 1 r 0

    I really like this. +1

    I knew someone would've already posted this!

  • JavaScript, 28 bytes


    For loops are often shorter than while loops.


    alert(x) returns undefined, which is falsy, so the bitwise or operator, |, casts it to 0. Thus, if x is "0", alert once, otherwise keep looping. Uses alert for STDOUT like this answer.


    for(x=prompt();alert(x)|x;);

    Shoot, you beat me to it. I was about to post exactly this! :) GG

    Wow, that's a good bit more clever than mine :) Have a +1!

    You don't need the trailing semicolon.

    @CᴏɴᴏʀO'Bʀɪᴇɴ What browser did you use? I tested it on Firefox and Chrome and I get a `SyntaxError` without it.

    @intrepidcoder Oh, sorry, my bad. My mind was in "trailing semicolons are useless" mode. ^^"

    Yeah, you need one because it's a for loop. :)

    Nice job, placing the alert in the condition was clever

  • Python 2, 29 bytes





    a=input()
    while 1:print a;1/a


    This terminates with a division error on 0, which is allowed by default.


    STDERR output is fine. The ><> answer uses it as well.

    This is brilliant ^_^

    Would while a print a work? Sorry, I dont know python.

    @RohanJhunjhunwala For 0, it wouldn't print anything, but it should print it once.

    @xnor oh, my bad.

    A new user (@SeoFernando) suggested a golf, replacing `a;a/1` with `a/a`.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used