33
\$\begingroup\$

What are the most important rules a first-time golfer in a given language should know? For instance, how do golfed programs usually take input and output?

Each language should have a single CW answer as the go-to explanation of the site rules for golfing in that language.

  • Use code snippet examples. Show, don't tell.
  • Be brief over being comprehensive.
  • Be accessible over being technically accurate.
  • Explain terms. Not everyone has heard of "STDIN" or "anonymous functions".
  • Don't include things applicable in any language like, "include a header with a byte count"
  • Don't include tricks for reducing byte count. That's for tips pages.

Alphabetical list of languages

The following Stack Snippet gives an alphabetized list of the languages that currently have guides.

function answersUrl(a){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf.meta&filter="+ANSWER_FILTER}function commentUrl(a,b){return"https://api.stackexchange.com/2.2/answers/"+b.join(";")+"/comments?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf.meta&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(a){answers.push.apply(answers,a.items),answers_hash=[],answer_ids=[],a.items.forEach(function(a){a.comments=[];var b=+a.share_link.match(/\d+/);answer_ids.push(b),answers_hash[b]=a}),a.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(a){a.items.forEach(function(a){a.owner.user_id===OVERRIDE_USER&&answers_hash[a.post_id].comments.push(a)}),a.has_more?getComments():more_answers?getAnswers():process()}})}function process(){var a=[];answers.forEach(function(b){var c=b.body;b.comments.forEach(function(a){OVERRIDE_REG.test(a.body)&&(c="<h1>"+a.body.replace(OVERRIDE_REG,"")+"</h1>")});var d=c.match(HEADER_REG);if(d){var e=d[1];a.push({lang:e,name:/<a/.test(e)?jQuery(e).text():e,link:b.share_link})}}),a.sort(function(a,b){return a.name>b.name?1:a.name<b.name?-1:0});for(var b=0;b<a.length;++b){var c=jQuery("#language-template").html(),d=a[b];c=c.replace("{{LANGUAGE}}",d.lang).replace("{{LINK}}",d.link),c=jQuery(c),jQuery("#languages").append(c)}}var QUESTION_ID=11924,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",OVERRIDE_USER=20260,answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var HEADER_REG=/<h\d>\s*([^\n]+[^\s])(?=\s*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"rel=stylesheet><div id=language-list><h2>List of languages</h2><table class=language-list><tbody id=languages></table></div><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td><a href={{LINK}}>Link</a></table>

\$\endgroup\$
  • \$\begingroup\$ How notable should a language be to have an answer here? For example Brain-Flak has some IO peculiarities that have been sorted out by Meta posts so it might be helpful to list them all in one place, but I doubt that any newcomers will be answering challenges in Brain-Flak. \$\endgroup\$ – Sriotchilism O'Zaic Mar 30 '17 at 4:15
  • 1
    \$\begingroup\$ @WheatWizard Any language should be fine to include. The target audience is first-time golfers for the language, which includes already-experienced golfers trying a new language. \$\endgroup\$ – xnor Mar 30 '17 at 4:17
  • 1
    \$\begingroup\$ @WheatWizard If everybody upvotes the answers for the languages they use, the most notable languages will rise to the top. This post could also use a Stack Snippet to create an alphabetical listing of languages, especially if it gets to multiple pages of answers. \$\endgroup\$ – DLosc Mar 30 '17 at 7:11
  • \$\begingroup\$ @DLosc I'm not convinced about the sorting. Guides could be upvoted for being well-written, or even just posted earlier. An alphabetical stack snippet would be great. Might you be able to add one? \$\endgroup\$ – xnor Mar 30 '17 at 8:36
  • \$\begingroup\$ This seems like a new source of inconsistencies between answers in different meta questions. Does the benefit really outweigh the downside? \$\endgroup\$ – Peter Taylor Mar 30 '17 at 9:27
  • \$\begingroup\$ @PeterTaylor Context. \$\endgroup\$ – Martin Ender Mar 30 '17 at 9:34
  • \$\begingroup\$ So, this is Document (I mean the feature only on SO) on PPCG? \$\endgroup\$ – lol Mar 31 '17 at 9:22
  • 2
    \$\begingroup\$ @xnor Added Stack Snippet, a simplified version of the leaderboard. Everyone: feel free to tweak it further, minify, etc. \$\endgroup\$ – DLosc Mar 31 '17 at 19:41
  • \$\begingroup\$ Your snippet isn't golfed at all. I feel betrayed. \$\endgroup\$ – Nic Hartley Apr 11 '17 at 1:52
  • 1
    \$\begingroup\$ I want to point out that command-line flags are no longer part of the score as per the latest meta consensus. This affects at least C#, Sed and Perl guides (didn't read through every post). \$\endgroup\$ – Bubbler Nov 27 '18 at 0:30

14 Answers 14

17
\$\begingroup\$

Haskell

Basic IO

In Haskell, a valid answer is usually a function, unless a full program is required by the challenge. Even if a challenge requires you to output an infinite stream of data (like all prime numbers), you can just write a function that returns an infinite list or string.

Functions

These kinds of functions are valid answers in a code golf challenge by default (based on this meta question):

  1. A named function (here f) with arguments:

    f x=x++map g x
    g n=div n 2*div n 3
    
  2. A named function (here f) without arguments:

    f=(++)=<<map g
    g n=div n 2*div n 3
    
  3. An unnamed function (here, the first line) without arguments:

    (++)=<<map g
    g n=div n 2*div n 3
    
  4. Binary functions can be defined as infix operators (here !):

    x!y=x++map g y
    g n=div n 2*div n 3
    
  5. For challenges where some output should be produced with out taking any input, the object itself counts as function which does not take any argument due to lazy evaluation (see this meta question):

    ['a'..'z']++['A'..'Z']++['0'..'9']
    

In all cases, you can have auxiliary functions and/or constants, here g, defined on separate lines or separated by semicolons (the former is preferred for readability, since the byte count is the same). Function definitions that use pattern matching are spread across multiple lines:

f 'A'='B'
f 'B'='A'
f x=x

All functions are curried (partially applied) by default, so the following four answers are equivalent:

f n x=map(take n)x
f n=map(take n)
f=map.take
map.take

Haskell has no concept of mutable values, so all functions must return their result instead of modifying the arguments in place.

The type of a function can be more general than the challenge requires, e.g. when the challenge asks to reverse a string, which in Haskell is a list of characters, then a function reversing a list with elements of any type is acceptable. If the type of a function can not be inferred without the function being called with an argument of the correct type, you can assume such a call exists (see this meta question).

Functions are allowed to wrap their return value in the Maybe Monad (see this meta question).

Full programs

Full programs either read their input from the user or take command line arguments, and print the result to the terminal. A full program is defined by main, and may of course include auxiliary definitions:

main=print.map g=<<readLn
g n=div n 2*div n 3

Input format is usually flexible, so you can take lists in the Haskell format [1,2,3] etc.

Hybrid answers

You can also use a function that prints its result to the terminal (and has a type like a -> IO ()), or a "function" that reads input from the user and computes a result (and has a type like IO a). These are rare in practice.

Libraries and extensions

Libraries can be imported with the import keyword at the beginning of a file:

import Data.List
f x=map(++x)$tails x

Imports must be included in your byte count. GHC extensions can also be used (but almost always cost too many bytes to be useful):

{-# LANGUAGE ParallelListComp #-}
f x y=[a-b|a<-x|b<-y,odd b]

Data types

Haskell has a rigid type system, so some specific tasks that are easy in scripting languages are cumbersome in Haskell. The most common issues are inputs/outputs of varying types (like "if input is a number, increment it, if it's a string, append a space") and arbitrarily nested arrays (like [[1],2]), neither of which are supported in Haskell. In such cases, you basically have three options:

  1. Use a built-in or imported type that implements this behavior: Either for varying types, Data.Tree for nested lists.
  2. Define a custom datatype. The most common approach to nested lists is

    data N=I Int|L[N]
    

    where Int can be replaced with whichever base type you need.

  3. Use string representations in some reasonable format.

All Haskell compilers implement type inference, meaning that you (usually) don't have to specify the types of functions and values, since the compiler infers them for you. It doesn't matter if the inferred type is more general than what is required.

Truthiness

Only values of type Bool have truthiness: True is truthy and False is falsy.

Compiler

If nothing else is stated a submission is assumed to run correctly in the current release of the Glasgow Haskell Compiler GHC. If your answer needs an other compiler or interpreter, e.g. Lambdabot, or relies on a specific GHC version, it should be submitted accordingly as e.g. Haskell Lambdabot or Haskell GHC 6.10.

Answers assuming a REPL (Read-Eval-Print Loop) environment are allowed though not encouraged. They too should be indicated accordingly, e.g. as Haskell GHCI.

Tips

Tips for golfing in Haskell are collected here.

\$\endgroup\$
10
\$\begingroup\$

Python

General I/O

Your submission should be a program or a function. It should print the output or return it. These example submissions compute the factorial:

# Program that prints
n=input();p=1
for i in range(1,n+1):p*=i
print p

# Defined function that outputs or prints
def f(n):
 p=1
 for i in range(1,n+1):p*=i
 print p

# Lambda function, no name needed
lambda n:reduce(int.__mul__,range(1,n+1))

# Lambda function, named to use recursive call
f=lambda n:1 if n==0 else n*f(n-1)

You may not expect input pre-written to a variable.

# Invalid, expects input in n
p=1
for i in range(1,n+1):p*=i
print p

Nor may you output just by saving the result to a variable.

# Invalid, saves result to p
n=input();p=1
for i in range(1,n+1):p*=i

Nor can the output just be the value of an expression like in the interactive shell.

Inputs

We're liberal about input formats. For example, if a challenge says to take a list of numbers, you may expect a Python list like l=[1,2,3], not like "1 2 3". So, a Python 2 program can do

l=input()

rather than

l=map(int,raw_input().split())

Likewise, when a program takes string input, you expect it in quotes to use input() in Python 2 rather than raw_input().

Version

Either Python 2 or Python 3 is fine. If the code only works correctly in a specific version, include the version number in the header.

Libraries

You may import libraries. The import statement counts as part of the code length. If it's a non-default library like scipy, call the language "Python with scipy" in the header.

Truthy/Falsey

Some challenges ask for a output to be truthy or falsey, which is determined by the value of bool(x). Only False, 0, None, and empty collections are Falsey, and the rest are Truthy.

More on functions

A function submission may include helper code outside the function, for example

import re;r=range
lambda l: ...

Functions may use extra optional arguments. For example, this factorial function submission expects a single number, but uses the optional input i to help recurse:

f=lambda n,i=1:1 if i>n else i*f(n,i+1)

You may not, however, require the function to be called with a specific extra argument, like "call this with 2nd argument 1" for

f=lambda n,i:1 if i>n else i*f(n,i+1)
\$\endgroup\$
  • \$\begingroup\$ Would it be worth mentioning in the More on functions section that functions need to be reusable but may assume that globals won't be touched by other code between function calls? \$\endgroup\$ – Martin Ender Mar 30 '17 at 7:54
  • 1
    \$\begingroup\$ Also you mentioned "Nor can the output just be the value of an expression like in the interactive shell." But REPL answers are allowed. And they may take input from the last evaluated expression. \$\endgroup\$ – Martin Ender Mar 30 '17 at 8:29
  • 3
    \$\begingroup\$ @MartinEnder I thought reusability came up too rarely to mention. And I hadn't considered someone would worry about additional code between function calls. Are these things a new user might be concerned with, perhaps based on other languages? About REPL, I'd consider "Python REPL" a separate language and so out of scope for this post. It could be rephrased, though I honestly don't want to encourage REPL answers. \$\endgroup\$ – xnor Mar 30 '17 at 8:32
7
\$\begingroup\$

APL (Dyalog)

Based on xnor's Python answer and user62131's Jelly answer.

General I/O

Your submission should be a program (tradfn), a function (tradfn, dfn, or tacit function), or an operator (tradop or dop). It should prompt for character and/or evaluated input from STDIN and/or take one or two arguments. It should return the result and/or print to STDOUT or STDERR. If nothing else is specified, programs print to STDOUT and functions return results.

Input

There are two ways to access STDIN: gets a single line of text as-is. gets a line of text and evaluates it. This is useful for numeric input, without having to use to execute the inputted text.

Output

Expressions which are not assignments will implicitly print to STDOUT with a trailing newline. In dfns and dops, such lines will also terminate the function/operator. Output to STDOUT can also be made explicit (e.g. for a partial result in the middle of an expression or to enable a dfn/dop to continue) with ⎕←. Output to STDERR is done with ⍞← and does not have a trailing newline.

Programs

Tradfn programs are simply one or more lines of code, where input (if needed) is gotten with and/or . On TIO, Tradfn program go in the Code field and the Header field must have a followed by a name for the program. The Footer field must have a . In the Input field, the first line must have the program's name to call it, and lines immediately after that will be the lines of input, if any.

Functions and Operators

Functions are either infix or prefix.

Tradfns functions and Tradop Operators include a header line which specifies their syntax. They may then refer to the names used in the header. They may do additional I/O in the manner of tradfn programs (see above). On TIO, the entire tradfn/tradop goes in the Code field, the header must begin with a and the last line must be a , but these three characters (including a newline before the last ) should not be counted into the submission length.

Dfn functions and Dop operators are one or more lines of code where the first line begins with { and the last ends with }, and they refer to their right and optional left arguments as and . Dops additionally refer to their refer to their left and optional right operands as ⍺⍺ and ⍵⍵. The first expression which is not an assignment will terminate the function, returning the result of that expression. They may otherwise do additional I/O in the manner of tradfn programs (see above). On TIO, the entire dfn/dop (including braces) goes in the Code field, and the first line must be preceded by a name and , e.g. MyFn←. The name and should not be counted into the submission length. In the Input field, the first line must have the function/operators's name to call it, followed and optionally preceded by arguments and, for operators, operands, and lines immediately after that will be the lines of additional input, if any.

Tacit functions are single lines which refer to their arguments as right and optional left arguments as and , and to the result of applying a sub-function f with same argument(s) as just f. While and may be used for additional input, they will only take input one, namely when the function is defined, and that input becomes constant for all applications of the tacit function. On TIO, the entire tacit function goes in the Code field, and must be preceded by a name and , e.g. MyFn←. The name and should not be counted into the submission length. In the Input field, the last line must have the function's name to call it, followed and optionally preceded by arguments, and lines before that will be the lines of additional input, if any.

Examples

These example submissions compute a dot product of two vectors:

Program (tradfn) that prompts for evaluated input and prints to STDOUT:

⎕+.×⎕

Program (tradfn) that prints to STDERR:

⍞←⎕+.×⎕

Function (tradfn) that prints to STDOUT:

x F y
x+.×y

Function (tradfn) that prints to STDERR:

x F y
⍞←x+.×y

Function (tradfn) that returns a result:

r←x F y
r←x+.×y

Operator (tradop) that prints to STDOUT:

(x F) y
x+.×y

Operator (tradop) that prints to STDERR:

(x F) y
⍞←x+.×y

Operator (tradop) that returns a result:

r←(x F) y
r←x+.×y

Function (dfn):

{⍺+.×⍵}

Operator (dop):

{⍺⍺+.×⍵}

You may not expect input pre-written to a variable:

⍝ Invalid, expects input in x and y
x+.×y

Nor may you output just by saving the result to a variable.

⍝ Invalid, saves result to r
r←⎕+.×⎕

Input formats

We're liberal about input formats. For example, if a challenge says to take a table of numbers, you may expect an APL vector of vectors like (1 2)(3 4) or an actual matrix, like 2 2⍴1 2 3 4, not necessarily JSON like [[1,2][3,4]]. So, an APL program can do

t←↑⎕

or

t←⎕

rather than

t←↑⎕JSON ⍞

Versions

Dyalog APL is backwards compatible. However, you may set the states of ⎕DIV (Division Method), ⎕FR (Floating-point Representation), ⎕IO (Index Origin), ⎕ML (Migration Level), and ⎕WX (Window Expose) to achieve the desired behaviour. You do not have to count the characters needed to set these. This is justified by the existence of systems where the needed setting is default.

Libraries

You may import libraries. The ⎕CY (Copy) statement counts as part of the code length, e.g. ⎕CY'dfns'.

A function submission may include helper code outside the function, for example

⎕CY'dfns'⋄N←NormRand
f← ...

Truthy/Falsey

Some challenges ask for a output to be truthy or falsey, which is determined by what conditionals like :If and dfn/dop guards (:) can accept. Simple arrays containing a single 1 or 0, with any number of dimensions (0–15) are acceptable for truthy and falsey respectively. All other values are non-Boolean.

Scoring

Dyalog APL has its own 256-character code page. If your code consists entirely of characters in this code page (most do), you can score the it as 1 byte per character.

If you need to use characters outside APL's code page for some reason, this is legal, but you must score your program using a UTF-8 byte count, in which non-ASCII characters count as 2 or more bytes. TIO's Dyalog Unicode will report both character count and UTF-8 byte count on the top left of the Code field, in the format "X chars, Y bytes (UTF-8)".

Three primitives (built-ins) added in each of versions 14.0 (, , and ) and 16.0 (, , and ) are not included in the code page, and may therefore not be used in 1 byte per character submissions without counting each as its shortest multi-character alternative:
⎕U2338⎕U2364⎕OPT
⎕U2286⎕U233A⎕U2378
Also, remember that these longer names need to be followed by a space if the next character is alphanumeric. Note that the dyadic form of can be reached by setting ⎕ML←3 and using instead, however, you must account for all other changes due to ⎕ML changing.
You can now use all the built-ins by claiming use of SBCS.

\$\endgroup\$
6
\$\begingroup\$

JavaScript

This answer is highly based on the Python answer, so thanks to @xnor for setting that up.

Your submission should be a program or a function. It should print the output or return it. These example submissions compute the factorial:

General I/O

// Browser program that inputs with prompt and outputs with alert
n=prompt();for(p=i=1;i<=n;i++)p*=i;alert(p)

// Node.js program that takes input from process.argv and outputs with console.log
n=process.argv[2];for(p=i=1;i<=n;i++)p*=i;console.log(p)

// Function that outputs with console.log (in a browser you could also use alert)
function(n){for(p=i=1;i<=n;i++)p*=i;console.log(p)}

// Function that returns the value
function(n){for(p=i=1;i<=n;i++)p*=i;return p}

// Function that returns, named to use recursive call
f=function(n){return n?n*f(n-1):1}
function f(n){return n?n*f(n-1):1}

// ES6 arrow function
n=>{for(p=i=1;i<=n;i++)p*=i;return p}

// ES6 arrow function, named to use recursive call
f=n=>n?n*f(n-1):1

Your may not expect input pre-written to a variable.

// Invalid, expects input in n
for(p=i=1;i<=n;i++)p*=i;alert(p)

Nor may you output just by saving the result to a variable.

// Invalid, saves result to p
n=prompt();for(p=i=1;i<=n;i++)p*=i

Nor can the output just be the value of an expression like in the interactive shell or browser console.

// Invalid, evaluates to result instead of outputting or returning
Array(+prompt()).fill().reduce(p=>p*i++,i=1)

Inputs

We're liberal about input formats. For example, if a challenge says to take a list of numbers, you may expect a JavaScript array like [1,2,3], not like "1 2 3". So, a function can do

function(a){return a.length}

rather than

function(s){return s.split(" ").length}

If you're using an arrow function and have multiple inputs, you can use currying:

// Non-curried arrow function
(a,b)=>a+10*b

// Curried arrow function
a=>b=>a+10*b

A curried function can be used by calling it once with each argument, e.g. f(1)(2) instead of f(1,2).

Version

If you use any features that were added in a recent version of ECMAScript (ES6: arrow functions, spread operator, template literals, etc.; ES7: exponentiation operator; etc.), include the ECMAScript version in the header. It's best practice to use titles such as JavaScript (ES6), JavaScript (ES7), etc. For future ECMAScript releases, you'll probably want to use the year name, e.g. JavaScript (ES2018), as ECMAScript has switched to this system of naming.

If, to the best of your knowledge, your code only works in a certain environment or browser, include that in the header instead, e.g. JavaScript (Firefox 44). If you submit a Node program, you may want to skip the "JavaScript" altogether and just use Node.js.

Truthy/Falsey

Some challenges ask for a output to be truthy or falsey, which is determined by the value of Boolean(x) (or equivalently !!x). Only false, 0, undefined, NaN, null, and the empty string are falsey, and the rest are truthy.

More on functions

A function submission may include helper code outside the function, for example

S=String;C=S.fromCharCode
l=> ...

In ES6 and above, functions may use extra optional arguments. For example, this factorial function submission expects a single number, but uses the optional input i to help recurse:

f=(n,i=1)=>i>n?1:i*f(n,i+1)

You may not, however, require the function to be called with a specific extra argument, like "call this with 2nd argument 1" for

f=(n,i)=>i>n?1:i*f(n,i+1)
\$\endgroup\$
5
\$\begingroup\$

Jelly

Jelly is a language designed for code golfing. Here's how our rules apply to it:

Program structure

PPCG questions normally ask for a "program or function" (and if they don't state what they're looking for specifically, they want a program by default).

A program is fairly straightforward in Jelly, which defines what a program is (a sequence of links, where the last one runs by default). A valid function submission is a link that can be called by number (i.e. using a builtin like 1Ŀ); in other words, it's a single line of your program. You can use extra lines (even when writing a function submission) to define helper links.

Taking input

A full program normally takes input from the command-line arguments ³, , , and so on. You may if you prefer use nilads like ɠ to read from the "standard input stream" (and a few challenges, especially older ones, may explicitly require you to do this). Note that you don't always have to write the ³ or explicitly; they'll be given as arguments to your program's main link by default.

If you're writing a function submission, you can take input via any of the above means. If your link isn't niladic, you can also inspect its arguments; a monadic link can take input via , a dyadic link via and . As with full programs, you don't always have to write the or explicitly as they're used as the default arguments in many contexts.

Producing output

There are two main ways to produce output in Jelly: on the "standard output stream", and via your program's return value.

When you're writing a full program, all the output goes to the same place; the program's return value (i.e. the current value at the end of its main link) will be written to standard output at the end of the program's execution. Basically all other methods of output (e.g. , Ȯ, writing a nilad out of context, etc.) will go to standard output directly. As such, all your output is combined in a single location, and you need to make sure not to produce extraneous output which will make your submission invalid.

When you're writing a function (i.e. link-based) submission, these two output locations (the link's return value, and standard output) are considered different, and you must nominate one or the other to count as the output to your program (the other will be ignored). This is the only real difference between a function and program submission in Jelly. (Note that a few questions may specifically require a full program, or specifically require a function.)

It's also legal to report output via the presence or absence of an error that crashes the interpreter; this is known as "outputting via exit status", with an exit status of 0 if the Jelly interpreter does not crash, and 1 if it does. As such, this method is only useful for outputting Booleans.

True and false

All values in Jelly are either truthy or falsey; the rule is that the number 0 is falsey, as is an empty structure (such as an empty list or empty string), and all other values are truthy. Note that a question that outputs a Boolean may require truthy/falsey output, consistent truthy/falsey outputs, or just any two consistent outputs; make sure you read the question to understand what it's asking for.

Scoring

Jelly has its own 256-character code page. If your program consists entirely of characters in this code page (most do), you can score the program as 1 byte per character. (Note that and newline are 100% interchangeable, and in fact are encoded the same way in Jelly's code page; you may use either of these characters to stand for the other in a submission.)

If you need to use characters outside Jelly's code page for some reason, this is legal, but you must score your program using a UTF-8 byte count, in which non-ASCII characters count as 2 or more bytes. (Mention this in the header, e.g. "100 bytes of UTF-8".) It's easiest to use a UTF-8 byte counting program in order to calculate the count exactly, as this is fairly difficult to do by hand.

\$\endgroup\$
5
\$\begingroup\$

Brain-Flak

Input

Input in Brain-Flak will be passed as command-line arguments to the interpreter. (On Try it online this doesn't work and instead they have to be put into the Input field with a whitespace separator) They will appear on the active stack at the beginning of execution.

If a challenge calls for a specific number of inputs they can be passed in any order you choose.

If the challenge requires you to take list or array of items you can have the items all passed as separate command-line arguments.

For example if the challenge is to sum up all the numbers in a list, the following code is valid:

(([]){[{}]{}([])}{})

Output

For Brain-Flak whatever is printed at the end of the program is the output, this does not include the offstack. You may leave anything you wish on the offstack at the end of execution.

For truthy and falsy values only the top item is considered. If the top item is zero, it is falsy otherwise it is truthy.

For example:

5
0
6

is True


0
1
4

is False

Because Brain-Flak's stacks are padded with an infinite number of zeros, an empty stack is considered a zero and is thus falsy in Brain-Flak.

The same does not hold for numeric values. For instance if you must output 5 you may not output:

5
1
0

However the stack is still padded with infinite zeros so when a zero is required for output the empty stack is acceptable.

\$\endgroup\$
4
\$\begingroup\$

PowerShell

Your submission should be a program or function. It should print the output or return it. Since an implicit Write-Output happens when a script finishes execution, simply leaving the result on the pipeline also suffices.

These example submissions compute the factorial:

General I/O

# Program that prints (implicitly), takes input via command-line arguments
param($n)$p=1
for($i=1; $i -le $n; $i++){$p*=$i}
$p

# Named function that returns, could also be "filter f($n){"
function f($n){
  $p=1
  for($i=1; $i -le $n; $i++){$p*=$i}
  $p
}

PowerShell does have the equivalent of a "lambda" or "unnamed" function via script blocks, but they are an advanced concept and (generally) not useful in code-golf, and so aren't covered here in this introductory topic.

You may not expect the input to be pre-stored in a variable

# Invalid, assumes the input already exists in $n
$p=1
for($i=1; $i -le $n; $i++){$p*=$i}
$p

Nor may you output by just saving the results in a variable.

# Invalid, simply saves results to $p with no output
param($n)$p=1
for($i=1; $i -le $n; $i++){$p*=$i}

Inputs

We're pretty loose with input formats. For example, if a challenge says to take in a list of numbers, you can expect input as a PowerShell array like $l=@(1, 2, 3), not like "1 2 3". So, for this example, a PowerShell program can do

param($l)$l.GetType()

and expect that the output will say it's of type System.Array.

However, in general, it's frowned upon to take in "a list of numbers" as separate command-line arguments and use the built-in $args as the array. This is allowed in some circumstances; ask on the particular challenge.

Version

The latest version of the open-sourced repository is generally assumed, and is the version used on the "Try It Online!" site. In general, versions are backwards compatible, so if there's a feature in v2, for example, it should also be available in the latest version, and you shouldn't need to specify.

Libraries

You may import libraries and .NET features. The import commands, like Add-Type -A System.Windows.Forms, or static calls like [system.math]::Floor(), must be included in your byte count. If it's a non-default library, like the PowerShell Community Extensions, call the language "PowerShell with PSCX" in the header.

Truthy/Falsey

PowerShell is strictly typed, but it attempts to dynamically cast on the fly as necessary. For PowerShell data types, the following code snippet is used to determine if something is truthy or falsey:

if($x){
 "True"
}
else{
 "False"
}

This means that 0, $false, "" (empty string), @() (empty array), $null, and variables set to those objects (including uninitialized variables, which default to $null) are falsey, and everything else is truthy.

Most of the formatting of this post comes from @xnor's Python answer. Thanks!

\$\endgroup\$
4
\$\begingroup\$

Perl

Version

The perl interpreter, by default, only turns on features compatible with the oldest possible version of the Perl specification. If you want newer language features (which is very common in golfing), you can request them at no penalty using command-line options. For example:

perl -M5.010

A few answers won't work in the newest versions of Perl, due to features which are now disabled by default. This most commonly comes up in the case where you want to interpolate Perl code into a regular expression (a combination of two common Perl golfing tricks). This is legal as long as you target your code at a version of Perl where the feature was enabled by default (and don't use any newer features). If you're using a version other than the most recent, you should mention it in the submission's header.

Program structure

The vast majority of questions on PPCG ask for a "program or function". (If a question doesn't specify what sort of submission is requested, it wants a program or function by default.)

A program (or "full program") doesn't need any sort of header or footer, and doesn't need a shebang; it's just a sequence of statements:

my $x = 4;
print $x

Most PPCG submissions in Perl are programs. If you want to write a function for some reason (or if the question specifically requests functions), you can name it:

sub f{"Hello, world!"}

but you don't have to, because returning a subroutine reference is also a legal sort of function:

sub{"Hello, world!"}

Taking input

If you're writing a program, you can take input from the default input streams:

<>

or from the command line:

$ARGV[0]

All forms of input effectively boil down to one of these in Perl. However, you can, at a byte penalty, use command-line options to turn on explicit input. The -a, -p, -n, and -i options all give you access to a form of implicit input. However, on PPCG, the use of command-line options like these carries a byte penalty when submitted to a question. -a, -p, and -n can be merged with other options (such as the -M5.010), and thus cost you 1 byte each. -i can't be, and thus costs 3 bytes (the -, the -i, and the space that separates them from other options).

If you're writing a function, you can also of course take input via the function arguments, e.g.:

$_[0]

or

@_

Note that you can't just assume that input is present in a particular variable (unless you use an option like -a or -n to put it there).

Producing output

In a program, you can produce output via printing it on the default output stream:

say"Hello, world!"

or on the warning/error output stream:

warn"Hello, world!"

or via setting the program's exit code:

exit 1

You can also output via using these methods indirectly; for example, assigning to $\ in order to affect the implicit print statement implied by -p is legal, and causing an error to affect the program's exit code is also legal.

If you're writing a function, you can use any of the above methods. You may also output via the function's return value:

return 4;
4 # at the end of the function

or overwrite @_, allowing the function's caller to read the output via the side effect on the input it was given:

$_[0]=4;

True and false

In Perl, almost all values are truthy (and thus are legitimate "true" outputs for a question asking for truthy or falsey values). There are precisely four falsey values: '' (the null string), 0 (integer zero), '0' (stringification of integer zero; equivalent to it in most contexts, including here), and undef (the undefined value); everything else is truthy. Note that if a question is asking you for a Boolean output, it might want any truthy/falsey value, a consistent truthy/falsey value, or just any two consistent values; read the question to see what is needed.

Code scoring

A submission in Perl typically looks something like this:

Perl, 10 + 1 = 11 bytes

$_=reverse

Run with -p (1 byte penalty).

Here, the "10" is the number of bytes in the submission itself, and the "1" is the number of bytes in penalties for command-line options, making a total of "11". In practice, Perl submissions nearly always use options like -p, but if you happen not to need any you can leave the penalties out of the header.

Perl programs nearly always use ASCII characters. If you're using non-ASCII characters, Perl will by default interpret them as being in a single-byte codepage which is consistent with ASCII, and has unknown (but consistent) characters in the top half. As such, it's worth looking for a single-byte codepage that has all the characters you need; Perl will treat this as opaque, and thus will accept any of them.

If you need to use Unicode for some reason, you're likely going to have to pay a byte penalty for command-line options to turn on Unicode; -Mutf8 costs 7 bytes, -C costs 3 (plus the length of the argument you give it). As usual, these counts are determined via working out how much longer the Perl command line has to be to fit the option onto it.

\$\endgroup\$
4
\$\begingroup\$

Bash

Scoring

Typically counted in bytes. Bash programs don't need a trailing newline, so don't count this if your editor adds one automatically.

If your entry only uses builtin features (use type -a <command> to find out), then you can claim your entry as Pure Bash. However if your entry calls external binaries (e.g. paste from coreutils), then your entry should mention this in the header, e.g. Bash + coreutils.

Truthy/Falsey

This is a little odd in shell-type languages. Shell commands - be they external binaries or shell builtins - return a status code between 0 and 255. Typically 0 indicates success whereas any other number indicates some error. The return code can be accessed in the $? variable. For example grep returns 0 if it finds a match and 1 if not:

$ echo haystack | grep -q needle
$ echo $?
1
$ echo haystack | grep -q hay
$ echo $?
0
$ 

The flow control statements (including if) use these values accordingly:

$ if echo haystack | grep -q needle; then echo Found it; fi
$ if echo haystack | grep -q hay; then echo Found it; fi
Found it
$ 

So TRUE = 0, and FALSE = anything else - upside down, right? You can see this even in the true and false builtins:

$ true
$ echo $?
0
$ false
$ echo $?
1
$ 

If this wasn't confusing enough, the (( )) arithmetic expansion test may be used to produce a return code. Internally these operate using the more usual TRUE = 1/FALSE = 0 paradigm, but this is switched for when the result of an expression is returned out of the (( )). For example:

$ ((1))
$ echo $?
0
$ ((0))
$ echo $?
1
$ 

I/O

Both programs and functions may read from SDTIN and/or use positional command-line parameters $1, $2, etc (or $@ for them all).

For testing purposes, you may explicitly put values in the positional parameters using set -- <param1> <param2> ...

Output is typically to STDOUT. Any output to STDERR may be ignored as per standard rules.

Truthy/Falsey output may also be in the form of a shell return code as described above. This works for programs and functions. The return keyword may be used to explicitly return with a given status, but if it is not used, the status of a program or function will be the status of the last executed command:

$ f()(true;false)
$ f
$ echo $?
1
$ f()(false;true)
$ echo $?
0
$ 

I/O datatypes

This is pretty flexible. The most common (Unix) way to input/output a list is to make it newline-delimited - i.e. one item per line. However there is no reason why you couldn't use comma-separated values instead, if that is convenient for the given challenge. There is not really a right-or-wrong way to do this with shell scripts.

Versions

Version 4.0 and later have several more advanced features. Some that spring to mind:

  • Associative arrays
  • More expressive brace expansions
  • Regex conditionals
  • mapfile

Different OSes have different utilities. For example the Linux find is most commonly a version from coreutils. This is quite different to the BSD-flavour find on MacOS - even if the bash versions are the same.

\$\endgroup\$
3
\$\begingroup\$

C#

Basic Input/Output

Submission are either named functions, complete programs, or anonymous functions. Functions take input as parameters and generally return the result (sometimes ref or out parameters may be applicable). Programs take input either from 'argv' (command line arguments) or from 'STDIO' (Standard Input/Output).

These example solutions compute the factorial of an integer input. You can generally accept either the string representation of the integer (typical for a complete program) or an integer argument to a function or lambda expression.

// 'complete program' reading input from STDIN, writing output to STDOUT
static void Main()
{
    int n=int.Parse(System.Console.ReadLine()), // read an integer
        a=1; // accumulator

    for(;n>0;)
        a*=n--;

    System.Console.WriteLine(a);
}
// 'complete program' reading input from command line arguments ('argv') and returning via exit code
static int Main(string[]args)
{
    int n=int.Parse(args[0]), // read an integer
        a=1; // accumulator

    for(;n>0;)
        a*=n--;
    return a;
}
// recursive named function
int F(int n)
{
    return n>1?F(n)*n:1;
}
// recursive named function (C# 6 'expression bodied' syntax)
int F(int n)=>n>1?F(n)*n:1;
// iterative anonymous typed lambda expression
(int n)=>
{
    int a=1;

    for(;n>0;n--)
        a*=n;

    return a;
}
// recursive named lambda expression (these are of no use in C# golfing)
System.Func<int,int>F=null;
F=n=>n>1?F(n)*n:1;

You may not have anonymous, untyped lambdas as you may see in other languages (e.g. x=>x*x would have to be (int x)=>x*x), as the type information can change the behaviour of the code, and as such is required to be unambiguous.

Version

C# has had about 2 breaking changes in its lifetime, and none of them have much bearing on golfing, so just use the latest: there are lots of potentially useful things in C# 6 and C# 7 to explore. Note that C# 7 tuples can't really be used at the moment because they require external libraries.

Libraries

Generally, everything you could possibly want to use is in mscorlib, the library that is (by default) automatically included by the compiler (csc (.NET) or mcs (Mono)), so it is rare to need any external DLLs.

Note that using external DLLs requires compiler command-line arguments, and these must be added to your byte count.

csc /r:OxyPlot.dll main.cs

Some common .NET DLLs do not need these arguments when using csc: https://stackoverflow.com/questions/2356180/no-need-to-reference-to-windows-forms-assembly

using directives also count toward your byte count:

using System.LINQ;
using C=System.Console;

Truthy/Falsey

In C#/.NET, truthiness and falseness are defined by the true and false operators, which (unless you define them on your own classes) are only defined for the bool data type.

If you are asked to produce a truth/falsy value then it must be something you could use in an if statement, which would be the bool values true and false, or a manually defined class (but this is unlikely ever to appear in code-golf). You can't, for example, return 1 for true and 0 for false, unless the challenge explicitly allows you to.

Try It Online

Remember that most people won't be running your code from an IDE, they will just Try It Online. TIO has Mono, and .NET CORE with C# 7.

In the past there have been some discrepancies between Mono and .NET compilation, notably with goto statements, so it's always worth checking that your code runs as expected to avoid confusion. And everyone appreciates a Try It Online link in a good answer!

\$\endgroup\$
  • \$\begingroup\$ 1. Separate but consecutive code blocks merge together unless you put something in between them. An HTML comment is a useful separator. 2. The two "complete program" examples are missing either a using System; or the fully qualified System.Console.WriteLine. (And Write is golfier than WriteLine...). 3. The "recursive named lambda expression" isn't recursive. 4. I don't understand what you're trying to say in the section on truthy/falsy, but I'm pretty sure it's wrong because it makes no mention of the bool type. \$\endgroup\$ – Peter Taylor Mar 30 '17 at 9:24
  • \$\begingroup\$ @PeterTaylor thanks, some of those were crass omissions. The true/false stuff isn't wrong, but was certainly silly not to mention bool. (Also, these are community wikis, I think the idea is everyone chips in, so feel free to make any changes you like, I just put that out to get things moving) \$\endgroup\$ – VisualMelon Mar 30 '17 at 9:46
3
\$\begingroup\$

Sinclair ZX80 BASIC (4K ROM)

Background

The ZX80 BASIC has a limited interpreter which lacks many keywords and has only upper-case characters and an inversed version of those upper-case characters. Its character set is non-ASCII compliant, and generally will only read and write to the screen[1] and cassette tape. There are no ways to draw to the screen without the enhanced ZX81 ROM unless one PRINTs to the screen, or works out where the DFILE (screen location) is in RAM and POKEs individual bytes to the screen. The recent ZXPand allows your ZX80 to read and write to an SD card, although this requires a special kit for the ZX80. An emulator such as EightyOne will simulate a real ZX80 with a ZXPand.

Program that prints

 10 PRINT "HELLO MUM"

Sub routines

 10 PRINT "HELLO ";
 20 GO SUB 100
 30 STOP
100 PRINT "MUM"
110 RETURN

Variables

 10 LET A$="HELLO "
 20 LET B$="MUM"
 30 PRINT A$;B$
 40 LET X=100
 50 LET Y=200
 60 PRINT X,Y

Loops

 10 FOR I=0 TO 10
 20 PRINT I,;
 30 NEXT I

Or if you don't want to count up in steps of 1 then

 10 LET I=0
 20 PRINT I,;
 30 LET I=I+2
 40 IF I<10 THEN GO TO 20

Reading the keyboard

 10 INPUT A$
 20 PRINT "YOU TYPED THE FOLLOWING STRING:"
 30 PRINT A$
 40 INPUT A
 50 PRINT "YOU ENTERED THE FOLLOWING INTEGER:"
 60 PRINT A

Please note there is no variant of INKEY$ or GET statement on the Sinclair ZX80 with 4K ROM.

Handling floating point numbers

Well, this is a tough one but let's assume that you want to print prices of items that are priced from £0.01p through to £327.67p, here is one way of doing it:

 10 INPUT M
 20 LET M=ABS(M)
 30 LET S$="."
 40 PRINT M/100;S$;
 50 LET R$=STR$(M)
 60 IF M<10 THEN PRINT "0";
 70 IF M>99 THEN LET R$=TL$(R$)
 80 IF M>999 THEN LET R$=TL$(R$)
 90 IF M>9999 THEN LET R$=TL$(R$)
100 PRINT R$

Basically, do them maths in integers, print your results divided by 100, pass your M variable to a string and shift the string left one character based on the value of M until you get to your pence. Or if M<10 then print a leading zero. I'm sure that you can think of a better solution to break the 327.67 barrier with this above symbolic listing.

Truthy/Falsey

The ZX80 [i]returns[/i] -1 if true or 0 if false. In order to do a not equals, one must use the following:

 10 LET A$="1"
 20 LET B$="2"
 30 IF NOT A$=B$ THEN PRINT "NOT EQUALS"
 40 IF A$=B$ THEN PRINT "EQUALS"

Animation

This is not really possible without using machine code as the screen is switched off whilst the BASIC interpreter computes. You will only get a static screen when waiting for a keyboard input with INPUT.

Color [SIC] text/graphics

The ZX80 has only a monochrome display

Obfuscating and minimizing listings

The ZX80 does not accept BASIC minimization or multi-statemented lines, like:

 10 PRINT "HELLO MUM ";: GO TO 10

White spaces are automatically added when typing in your listing, and there are no keyword abbreviations. BASIC keywords are tokenized.

Standard input/output

This wasn't even a thing in 1980, so standard in could mean reading from the keyboard to a variable or from a cassette player (or the virtual equivalent) - and standard out could mean writing to the screen, or storing data to a variable, or recording data to a cassette tape (or again virtual equivalent).

Unconditional loops

Yes, the GO TO keyword exists.

Object Orientation

Err...

\$\endgroup\$
  • 2
    \$\begingroup\$ "Object Orientation: Err..." \$\endgroup\$ – cat Apr 4 '17 at 14:36
  • 1
    \$\begingroup\$ Can you address scoring in this post? IIRC its a tokenised language, which complicates things \$\endgroup\$ – Digital Trauma Apr 7 '17 at 3:18
  • \$\begingroup\$ I did ask for there to be code-golf alike challenges and 'one-liners' on the Retro Computing Stack Exchange, but apparently this would not be relevant to Retro Computing. The ZX80 and other 8- and 16-bit machines are mostly not a good fit for code-golf - however this situation could be simplified if the Code Golf stack exchange would allow for 8-bit specific categories and challenges as a trial, that way we could resolve all of the anomalies that retro/ancient 8-bit tech presents. \$\endgroup\$ – Shaun Bebbers Apr 7 '17 at 8:19
  • \$\begingroup\$ I can only approximate byte counts at the moment I haven't found a good resource for ZX80 programming, so based on the ZX81 byte count for symbolic listings, it's 3 bytes per line plus 1 byte per key-press. White spaces can be ignored unless they are within a string literal. For instance, if you press Y for PRINT it is immediately proceeded by a white space that you cannot delete without also removing the PRINT keyword \$\endgroup\$ – Shaun Bebbers Apr 7 '17 at 8:22
3
\$\begingroup\$

Sed

As sed doesn't have functions, submissions will be complete programs, with input and output via the standard streams.

Programs with no input

Sometimes a question asks only for output, and doesn't specify providing any input. Because sed is incapable of producing any output unless there's at least one line of input, you should assume in these cases that the input consists of a single newline character.

Scoring

Programs are normally in single-byte character encodings, so counting characters is generally sufficient. Interpreter flags need to be added, as normal; for example, +1 if your program requires -r.

Numeric I/O

Unary is the most useful numeric format for sed, if the question doesn't specifically bar that. It is possible to use sed for arithmetic; although it's unlikely to win any , it's certainly an entertaining challenge!

Tips

See tips on the main site.

\$\endgroup\$
  • \$\begingroup\$ Sed doesn't require programs to have a trailing newline \$\endgroup\$ – Digital Trauma Apr 7 '17 at 3:15
  • \$\begingroup\$ Sed has no native truthy/falsey concept \$\endgroup\$ – Digital Trauma Apr 7 '17 at 3:16
2
\$\begingroup\$

CJam

Input

CJam submissions can be full programs that take input using q (read whole input), r (read whitespace-separated token), and l (read line). Alternatively, they can take input from the command line arguments using ea (push command-line arguments).

These are all valid CJam submissions:

q S/ :i ~ +
ri ri +
ea :i ~ +

CJam answers can also be in the form of blocks, which are code objects. Including these in a full program pushes them to the stack where they can be executed with ~.

{ + }

CJam blocks can also be named by appending :? to a block, where ? is any capital letter:

{ ) \(\ 1$ {K}& }:K

Blocks can take input using q, r, and l, but full programs may not take input from the stack.

Output

Full programs and blocks can both output via o (output), n, (output with trailing newline - this is only available on TIO), and p (output string representation with trailing newline).

ri ri + o

However, full programs may also rely on CJam's automatic printing of the stack. Keep in mind that the stack is printed with a trailing newline, though this is usually unimportant in most challenges:

ri ri +

Blocks may output with o, n, or p, or by leaving values on the stack:

{ + n }
{ + }

Scoring

CJam has no special character encoding. All commands are one byte, but you might run into Unicode in string or character literals. You can use a site like https://mothereff.in/byte-counter to check your code length in UTF-8.

e# 8 bytes
ri ri +
e# 15 bytes
ri ri + '😀

Implementation

There is a JavaScript implementation of CJam on https://cjam.aditsu.net. You can also use the Java interpreter from https://tio.run/nexus/cjam, or download it from https://sourceforge.net/p/cjam. Note that the TIO version supports some extra features (like n) that the aditsu.net and SourceForge versions do not.

\$\endgroup\$
0
\$\begingroup\$

H

(The question only said "languages", so a language like H should be fine.)

H programs contain almost nothing but inputs, outputs, and variable initialization. However, it is still very powerful for writing programs. This is a trivial one-line cat program:

# This is a one-line cat program, which copies its input to its output.
input("Input a line:";a);
print(a);

A valid answer (like the one above) can only interact with users from the standard I/O; i.e. there is no way to break that rule of interaction.

Example:

#This is valid
print(-2+4);

Try this in an H implementation, and this might astonish you.

Implementation

There are implementations for H in this website. Mentioning all of them is quite trivial.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .