550
\$\begingroup\$

Notes

  • This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional questions.

  • This is no longer a , nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

  • All answers should include the name of the programming language at the top of the post, prefixed by a #.

  • Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

  • Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

  • The snippets do not need to be related. In fact, snippets that are too related may be redundant.

  • Since this is not a contest, all programming languages are welcome, whenever they were created.

  • Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

  • Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('<li><a href="/a/' + data.items[i].answer_id + '">' + temp.innerText || temp.textContent + '</a>');}}})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul>

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Why preserve a tag for one question, is it still bad for SE to have untagged question? \$\endgroup\$
    – l4m2
    Commented Jan 4, 2023 at 1:43

243 Answers 243

1
2
3 4 5
9
32
\$\begingroup\$

Pyth

For further snippets, I'll be posting solutions to golf challenges and a link to the problem.

Length 17:

<ussC,cG\_GUQ*zQQ

Find the first n characters of the infinite sequence formed by repeating the input string forever, then filling in its underscores with the sequence itself, then repeating that forever.

Fill In the Blanks

Length 14:

#QX=Qhf>FT.:Q2

Given a list of unique elements, sort the list by swapping pairs of neighboring elements, printing out all intermediate results.

Rearranging a set of numbers into order

Length 13:

?hu]+HG_UQYQY

Create the following structure: [0, [1, [2, [3]]]].

Home on the Range of Lists

Length 12:

uxyG*HQjvz2Z

XOR multiplication.

XOR multiplication

Length 11:

lfqSzST.:wz

Count how many substrings of the first word are anagrams of the second word.

Detecting anagrams within a Parent String

Length 9:

fqJjQT_J2

Find the lowest base in which the input is a palindrome.

Lowest-Base Palindrome

Length 5:

!%lQ1

Check whether the input is a power of 2. Take the log base 2, take the result mod 1, and take the logical not.

Check whether an integer is a power of 2 without using +,- operations

Length 4:

sjQ2

Calculates the hamming weight of the input by adding up the base 2 representation of the input.

Count the number of ones in unsigned 16 bit integer

Length 3:

^G2

^ on sequence, int, gives the cartesian product of the first argument with itself n times, where n is the second argument.

In this case, since G is the alphabet (abcdefghijklmnopqrstuvwxyz), ^G2 gives all 2 letter strings, aa through zz.

Length 2:

lT

l, while normaly serving as len(), can also be used as log base 2. Since T is the variable initialized to 10, this prints 3.3219280948873626, log base 2 of 10.

Length 1:

H

H is the empty dictionary (hash-table) in Pyth, and is the only way to get a dictionary in Pyth, short of using v (eval) or $ (Python literal).

Factoid:

Pyth has no multi-character constructs other than literals. Also, Pyth compiles essentially one-to-one into Python.

\$\endgroup\$
2
  • \$\begingroup\$ Was your factoid added before you have commands that start with .? \$\endgroup\$
    – Leaky Nun
    Commented May 24, 2016 at 12:41
  • \$\begingroup\$ @LeakyNun Yes.. \$\endgroup\$
    – isaacg
    Commented May 24, 2016 at 21:21
32
\$\begingroup\$

Ruby

Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.

Link for myself, or anyone who wants to contribute to this answer.

Length 19 (by a guest)

[1, 2].each{|i|p i}

Ruby supports for loops, but the .each method is preferred. The code in brackets is a block, essentially a single-use anonymous function. Blocks can take parameters, which are enclosed in pipe characters. The p is a shortcut for puts [something].inspect. The .inspect method is a variation of .to_s which provides more details about the object.

Length 18

%i[I love you too]

This is an example on how to create an array of symbols, the result would be: [:I, :love, :you, :too]

Length 17

'1.34'[/(\.\d+)/]

This is an example on creating snippet then parse it using regular expression. This regular expression means get any dot \. that followed by one or more (+) digit (\d) then capture it. The result of this snippet is a new string containing .34.

Length 16

'abcdefg'[3..-1]

This statement means, create a string containing abcdefg, then get the fourth (4th = 3) character until the end (last = -1). Another example: [3..3] get the fourth character only (d), [3..5] get the fourth until sixth characters (def), [-3..-1] get the third last character until the last character (efg).

Length 15

%w{i love you!}

This is a shortcut to create array of words (string), that is equal to ['i', 'love', 'you!']

Length 14

[1,2,3,4]*'ab'

Array multiplication with a string equals to call a .join method, the result of this snippet is 1ab2ab3ab4, that also equal to calling: [1,2,3,4].join 'ab'

Length 13

y=->x{x**3}

This is an example on how to create a lambda (or sometimes called anonymous function) using stab operator ->. This statement means create an anonymous function that accept one parameter x that returns x*x*x, then assign this function to a variable named y. Any lambda can be called using .call method, for example:

y = ->(x){x**3}
y.call 8 # 512

This is equal to:

y = lambda {|x| x**3}

Length 12 (by Devon Parsons)

puts "#{$$}"

This snippet shows a couple things. As shown below, puts writes to STDOUT. Code encapsulated in #{ code_here } is evaluated when the string is created, provided the string is made with double quotes. And ruby stores a bunch of useful global variables in double-character shorthand: For example, $~ is the most recent regex match, and in this snippet, $$ is the current process ID. So this snippet writes the current process' ID to STDOUT.

Coincidentally, the ID is of type Fixnum. The string interpolation automatically calls the to_s method on the evaluated code, and to_s by convention returns a string interpretation of the object.

Length 11

x={a:1,b:2}

The statement above is one (of many way to create a Hash or commonly called associative array), to access the value, you can type x[:a], where :a is a symbol (explained in Length 2). To set a value you can type x[:key_name] = 'yayy'. The key of a Hash could be anything not just symbol. Another popular way to create a Hash is using => symbol, for example:

x = { 'a' => 123, 456 => [7,8,9], c: 'wow' }
# x['a'] == 123
# x[456] == [7,8,9]
# x[:c] == 'wow'

Length 10

[*(8..11)]

In this snippet, that statement has the same effect as typing: [8,9,10,11]. The 8..11 part is called Range object. The * operator is the splat operator, in this part, the operator has the same effect as .to_a to array conversion (8..11).to_a.

Length 9

def x;end

This is an example on how to create a function, that example is the same as:

def x
end

To fill the function content, you may type it before the end keyword, for example:

def x
  puts 'the x function has been called'
  123
end

Anything that typed before end keyword would be returned, so in this statement y = x, the y variable would contain 123.

Length 8

9.to_s(2)

This is an example on how to perform base conversion from base-10 integer to binary number, the result would be 1001. You can change number 2 into another base, and .to_i can have parameters too, to parse from string to number, for example '1101'.to_i(2) that would return 13.

Length 7

__END__

__END__ is a line keyword that denotes the end of regular source code, the lines below that line wont be executed and would be gathered in DATA string constant.

Length 6

rescue

The rescue keyword is Ruby's keyword to catch raised exception, we could use this as one-line, for example: x = 1/0 rescue 2, that would set x into 2, or we could use it within begin and end keyword, for example:

begin
  1/0
rescue ZeroDivisionError
  puts 'zero division detected
end

You can find more information about ZeroDivisionError here.

Length 5

BEGIN

BEGIN is a keyword that will execute following code-block before anything else withint the script, for example puts 'b'; BEGIN { puts 'a' } would give an output: a then b. There are also END keyword that executes next code-block before program termination.

Length 4

puts

This function would print a newline on the console, if you add anything as parameter for example: puts('A') or puts 'A', this would print an A character then a newline.

Length 3

'A'

Single quote is one way to create a string, there are another way such as double quote, always use single quote for better performance when no interpolation needed. To get the code-point value of a single string, use .ord method.

Length 2

:x

This is an example on how to create a symbol. Symbol starts with colon followed by quoted string, underscore or alphabet. Symbol is an object to hold immutable string, that normally used as hash's key. To convert it to string, use .to_s method.

Length 1

1

This is an example on how you make a Fixnum object, fixed number is an integer. everything is an object in Ruby, they could have methods such as: 1.to_f would return 1.0 a Float object, or 1.to_s would return "1" a String object.

Factoid

Gems is Ruby's package (library and programs) manager.

\$\endgroup\$
5
  • \$\begingroup\$ Kokizzu, why did you add so many snippets? You are only up to 13 votes \$\endgroup\$ Commented Feb 18, 2015 at 14:33
  • \$\begingroup\$ overexcited.. XD \$\endgroup\$
    – Kokizzu
    Commented Feb 18, 2015 at 15:41
  • \$\begingroup\$ Should be rolled back now that it's past 20! \$\endgroup\$
    – fede s.
    Commented Mar 24, 2016 at 0:32
  • \$\begingroup\$ Ruby has so many awesome features! Why have I never bothered to learn to use it? \$\endgroup\$ Commented Nov 14, 2016 at 5:05
  • 2
    \$\begingroup\$ @ETHproductions I have no idea why Python was chosen over it as a learning language. Ruby is simpler at first and much more powerful after you learn the basics. \$\endgroup\$
    – anna328p
    Commented Nov 14, 2016 at 5:36
32
\$\begingroup\$

Rust

Rust is a general purpose, multi-paradigm, compiled programming language developed by Mozilla Research. It is designed to be "safe, concurrent, and fast."

Since Rust emphasizes stability, these snippets shouldn't be subject to change anymore.

Length 68

fn a<T:Default>(v:T,p:&dyn Display)->T{println!("{p}");T::default()}

For any Type T that implements the Default trait and that calls function a in your code, the compiler will create a dedicated function that only that type will call and use. This is called monomorphization.

At the same time, all these new functions accept a value p, as a fat pointer (A pointer to the value, and the display implementation of that value).

These new functions can display the value p by dynamic dispatch (invoked by &dyn Display).

Length 19

|x|print!("{}",x*2)

This is a closure, similar to a lambda or anonymous function in other languages. It takes one argument x and prints its doubled value. Note that the type for x was not specified. It will be inferred by the compiler automatically when this closure is called.

Length 15

enum X{A(u8),B}

This is an example of an enum, the other one of the two primary types of custom data structures. Enums can be one of a list of variants (here A and B) and can also carry data (here u8).

Length 14

struct X{a:u8}

A struct is one of the two primary ways of defining a custom type. It consists of a group of typed fields, which must all be initialized to construct a value.

Length 11

&mut String

This is the syntax for declaring a mutable reference, a key principle for memory and data management in Rust. It is enforced at compile time that at all times a value may either have only one mutable reference to it or arbitrarily many immutable references (written &String). This makes some code designs less easy to accomplish, but helps a lot to avoid bugs.

Length 10

Option<u8>

Rust doesn't have a null value like many other languages do. Instead, you use the Option enum (see snippet 15), which is either Some and contains a value, or None and empty.

Length 9

fn main()

The main() function is, well, the main function where the program begins. Here's the example of hello world (also automatically generated by cargo new as a template):

fn main() { println!("Hello, world!"); }

If saved as hello.rs, the source can be compiled and run using this command:

rustc hello.rs && ./hello

Length 8

fn x(){}

This is an example on how to create a function named x. The arguments can be written inside (), the statements or expressions can be written inside {}, and the return type can be given with a -> after the arguments, for example:

fn x(a: i32, b: i32) -> i32 {
    if a == 0 { return b; }
    a + b // equal to return a+b;
}

The return keyword is used to exit the function. Just like Ruby, the last expression at the end of the program will be returned when it is reached. Here's the exact same function without the return keyword:

fn x(a: i32, b: i32) -> i32 {
    if a == 0 { b } else { a + b }
}

By default, all functions return ().

Length 7

if x {}

This is the if syntax of rust, this part is similar to Go's if syntax. We could also write it like this:

let y = if z == 3 { 9 } else if z > 3 { 12 } else { 15 };

Length 6

print!

The print! and println! macros are the standard ways to produce output. They have a similar syntax to .NET's String.Format method. Here are some examples:

print!("{0} {1} {0}",123,234);     // 123 234 123
println!("{} {} {}",123,234,345);  // 123 234 345
print!("{a} {b} {c}",a=1,c=2,b=3); // 1 3 2

The {} symbols are called next argument specifier, {number} is a positional parameter, and {string} is a named parameter, we could mix any of them. To print the type of a value, you can use :? debug traits, see this link for more formatting traits.

println!("{:?}", 123 );
// 123i32

println!("{:?}", "abc" );
// "abc"

println!("{:?}", std::io::stdin().read_line() );
// some possible outcomes:
//  Ok("string that has been read\n")
//  Err(IoError { kind: EndOfFile, desc: "end of file", detail: None })

println!("{:?}", std::io::stdin().read_line().ok() );
// some possible outcomes:
//  Some("string that has been read\n")
//  None

println!("{:?}", std::io::stdin().read_line().ok().expect("Fatal: read_line failed!") );
// some possible outcomes:
//  "string that has been read\n"
//  thread '<main>' panicked at 'Fatal: read_line failed!'
//  {traceback elided}
//  ^ this one not entering the println! function

Note that print! is called with an ! at the end: this is because it is a macro instead of a function. Macros expand to regular Rust code during compilation and are a powerful tool for writing more flexible code. Here, this is utilized to check the format arguments at compile-time and to allow a variable number of arguments.

Length 5

stdin

The stdin is a function that could access the standard input (when called, it returns a std::io::stdio::StdinReader type), usage example:

let s = std::io::stdin().read_line().ok().expect("Fatal: read_line failed!");

Or we may type:

use std::io::stdin; // outside function
let s = stdin().read_line().ok()
               .expect("Fatal: read_line failed!");

The .ok() part would check if read_line failed and the .expect("Fatal: read_line failed!") part would exit the program when it does.

Length 4

true

Just like in other common programming languages, this is a value of type bool. As you can guess, the other value is named false.

Length 3

let

The let keyword is primarily used as to declare a variable; here's an example on how to use it:

let x = 1;
let (y, z) = (3, 4);
let a: u64 = 18446744073709551610;

The variables defined by the let keyword are immutable. To make them mutable, add the mut keyword, for example:

let mut b = 123;
b = 234;   

Length 2

""

This is an example of how to create an empty string slice (called &str). This string is saved in the program's binary, and cannot be mutated or deleted at runtime. There is another type of string in Rust, a mutable one, that is called String. To convert between &str and String use the .to_string() method, that copies the old string into another place so it can be modified (mutated). To convert a String to &str, use .as_slice() method.

Length 1

1

This an example of a valid number literal which will be of the type i32 by default. To force it to be of another type, use that type as a suffix such as u8, i8, u16, i16, u32, i32, u64, i64, usize, isize, f32 and f64.

Factoid

Rust has certain design philosophies:

  • Memory safety must never be compromised
  • Abstraction should be zero-cost, while still maintaining safety
  • Practicality is key
\$\endgroup\$
6
  • 2
    \$\begingroup\$ Tell me more... in, er, 2 characters..? \$\endgroup\$
    – Phil H
    Commented Jan 27, 2015 at 11:00
  • \$\begingroup\$ that's hard.. XD lemme study first in 5 minutes.. \$\endgroup\$
    – Kokizzu
    Commented Jan 27, 2015 at 11:01
  • \$\begingroup\$ I don't know if this could persist for a long time codebunk.com/b/55619431 for backup: pastie.org/9865143 \$\endgroup\$
    – Kokizzu
    Commented Jan 27, 2015 at 11:20
  • 2
    \$\begingroup\$ This is the first time I've heard about Rust. +1 for luring me in. Looking forward to seeing more. \$\endgroup\$
    – Alex A.
    Commented Jan 27, 2015 at 19:33
  • \$\begingroup\$ @Kokizzu CodeBunk persists for a long long time \$\endgroup\$
    – spicavigo
    Commented Apr 8, 2015 at 23:06
31
\$\begingroup\$

IBM Enterprise COBOL

Factoid: Whilst it is possible (twists and turns) to have a useful two-character program (to be the target of a CALL to a sub-program which doesn't otherwise exist yet), other than variations of the same thing, the next one would come in at 26 characters, and would be a variation which... doesn't work.

Plus that is not counting the mandatory seven blanks at the start of a line. And it would be severely abusing the language.

COBOL's not really so good for this challenge.

This is becoming interesting in itself. Although it will be a while before I can get the program to do something else, it is an interesting academic voyage of discovery.

Remembering that these are short, and abused, programs it is interesting that only valid COBOL can be ignored, if invalid it gets an S-level diagnostic, which is going too far. Some actually valid COBOL will not work without a full-stop/period, as I've noticed when trying to Golf(!) things previously.

Two characters

Excellent. Here's the two-character example. Remembering, sorry about that, that it must be preceded by seven blanks.

   ID

Doesn't look like much of a program. Certainly not much of a COBOL program. You do have to bend things a little.

Compile it, and these are the diagnostic messages you get:

 1  IGYDS1102-E   Expected "DIVISION", but found "END OF PROGRAM".
 "DIVISION" was assumed before "END OF PROGRAM". 

 1  IGYDS1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

                  Same message on line:      1 

 1  IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
 Program-name "CBLNAM01" was assumed. 

That gets you a Return Code/Condition Code of eight. Normally you wouldn't generate the code for, or attempt to execute, a program with an RC/CC higher than four. However, none of those messages affect the generated code (except the allocation of a Program-name).

What does the program do? When it is CALLed, it simply returns to where it was called from, in the normal manner.

How would you use it?

Whilst developing a program, you want to check out the control flow, but you haven't written a couple of the sub-programs yet. Simply copy the loadmodule (created by feeding the object code produced into the linkeditor/binder) to the name of the CALLed program and, assuming you are using Dynamic CALLs, you have a stub which is just going to give you back control. For a Dynamically-called program, the PROGRAM-ID (Program-name) is irrelevant, so it does not matter if you accept the generated name.

An equivalent "real" program would be this.

   ID DIVISION. 
   PROGRAM-ID. Anything.

Alternate two-character (didn't know about this before)

   FD

Diagnostics

    IGYDS1000-E   A "IDENTIFICATION DIVISION" header was not found 
    in this program.  It was assumed present. 

    IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
    Program-name "CBLNAM01" was assumed. 

 1  IGYDS1022-E   A data-name or file-name definition was found 
                  outside of the "DATA DIVISION".  Scanning was 
                  resumed at the next area "A" item or the start of
                  the next entry. 

 1  IGYSC1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

Note the lack of line-number for the first two messages. This time, with an ID, there is no line-number to associate those messages with.

Three characters also didn't know

    1 A

Diagnostics

    IGYDS1000-E   A "IDENTIFICATION DIVISION" header was not found 
    in this program.  It was assumed present. 

    IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
    Program-name "CBLNAM01" was assumed. 

 1  IGYDS1022-E   A data-name or file-name definition was found 
                  outside of the "DATA DIVISION".  Scanning was 
                  resumed at the next area "A" item or the start of
                  the next entry. 

 1  IGYSC1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

This program defines a group-item (valid for this purpose) but it is discarded.

Program operates as above.

Four characters

Since it is COBOL, we should see a full-stop/period at some time. Now.

   1 A.

Even though the line is discarded, it gets one less diagnostic because the program source now ends with a full-stop/period.

Five characters

We're up to five votes, so here's a five character program that is equivalent:

   ID FD

This operates in exactly the same way as the two-character example. FD is valid COBOL, so the compiler realises there is some stuff missing. Without it being valid COBOL, there would be an S-level message, and an RC/CC of 12. With it being a valid COBOL word, but obviously out of place, the third messages shows that it is just ignored.

 1  IGYDS1102-E   Expected "DIVISION", but found "FD".  "DIVISION" 
 was assumed before "FD". 

 1  IGYDS1082-E   A period was required.  A period was assumed 
 before "FD". 

 1  IGYDS1022-E   A data-name or file-name definition was found 
                  outside of the "DATA DIVISION".  Scanning was 
                  resumed at the next area "A" item or the start of
                  the next entry. 

 1  IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
 Program-name "CBLNAM01" was assumed. 

 1  IGYSC1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

Six characters

   ID 1 A

Combining a two character and a three characters, which need to be separated.

Diagnostics similar to the five-character solution.

Seven characters

   LINKAGE

That's a reserved-word used (followed by the word SECTION) to identify the data-items which are defined elsewhere and whose addresses are made available by a CALL from another program. Its inclusion doesn't affect our existing program :-)

Diagnostics

    IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
    Program-name "CBLNAM01" was assumed. 

 1  IGYDS1000-E   A "IDENTIFICATION DIVISION" header was not found
 in this program.  It was assumed present. 

 1  IGYDS1005-E   The "DATA DIVISION" header was not found.  A 
 "DATA DIVISION" header was assumed before "LINKAGE". 

 1  IGYDS1103-E   Expected "SECTION", but found "END OF PROGRAM". 
 "SECTION" was assumed before "END OF PROGRAM". 

 1  IGYDS1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

                  Same message on line:      1 

A little more interesting this time. That "Same message on line: 1" looks odd (as the other message it is the same as is also line 1) but that is because we only have a one-line program and there are two required full-stops/periods (should be one after the SECTION which isn't there and one to end the source program).

\$\endgroup\$
2
  • \$\begingroup\$ Needs more votes to show the true characteristics of COBOL. \$\endgroup\$
    – idrougge
    Commented Mar 12, 2017 at 3:22
  • \$\begingroup\$ "the next one would come in at 26 characters" and we have 30 votes. What now? \$\endgroup\$ Commented Feb 7, 2018 at 0:33
31
\$\begingroup\$

SAS

Factoid:

SAS is a data manipulation 4th generation language dating all the way back to 1966. Despite its age, it is still widely used to this day, particularly in financial and pharmaceutical environments where a large legacy codebase has been built up over the past few decades.

Length 1

;

To the best of my knowledge, this is the only complete and valid SAS statement of length 1 - a null statement.

Length 2

x;

SAS was born out of an effort to get code from one platform working on another. It has many OS-agnostic commands for interacting with the host operating system. The x statement is one of these. A null x statement opens up a command prompt / terminal for user input.

Length 3

%a:

As well as the primary language (consisting mainly of data steps, procs and global statements), a macro language was added in SAS 5. With 3 characters, we can define a 1-letter label for use with a macro %goto statement.

Length 4

run;

Analysts typically write SAS programs in an interactive environment (the SAS Enhanced Editor window). A run statement is required in order to tell SAS to execute all the (non-macro) code that's been compiled since the last run statement. As there is often a lot of back-and-forth editing and re-running of various steps within programs, it is quite common to see a run statement at the end of every data step and proc in a program, even though most of them are probably not necessary when running the whole thing from end to end.

Length 5

quit;

Some SAS procs support multiple sequentially executed run groups and will therefore not terminate until a quit statement is issued. Others do not and will throw an error if they receive a quit statement. Still others accept only a quit statement and will throw an error if they receive a run statement. Working out which are which can be rather frustrating for new users.

Length 6

set a;

SAS data steps usually operate in an implicit loop from an initial data statement to a final run statement (or the start of another data step, global statement, or proc). Each time a set statement is executed, SAS reads the next record from the input sas dataset(s) into an area of memory known as the Program Data Vector, where individual variables can be manipulated with data step functions until the end of that iteration of the data step is reached and the record is written to the output file or dataset. This process repeats until the last record has been read from the input dataset and duly processed.

Length 7

link a;

SAS has two different versions of goto !

link and goto statements will both send you to a label elsewhere in the data step, but the difference between them is what happens when you subsequently reach a (possibly implicit) return statement. If you last came from a goto statement, you go back to the start of the implicit data step loop for a new iteration, but if you last came from a link statement, you go back to the statement just after the (most recent) link statement and continue the current iteration.

Although it stops short of explicitly advising programmers not to use these statements, the SAS help file diplomatically points out that

GO TO statements can often be replaced by DO-END and IF-THEN/ELSE programming logic.

Length 8

%let a=;

This creates/overwrites a zero-character macro variable a. It may be local or global, depending on whether the %let statement runs within a macro or in open code. It can be referred to elsewhere in the program as &a. Syntactically, this is not a special case - you never need to use quotes when defining macro variables this way, unless you want to produce a string that contains them! Also, all macro variable values are trimmed when assigned, so inserting whitespace between = and ; has no effect.

Length 9

a="""''";

In a data step, this assigns the value "'' to the variable a. SAS parses the outermost pair of double quotes first, then replaces each inner instance of two consecutive double quotes with a single double quote. The consecutive single quotes are unaffected. The converse happens if you replace the outer double quotes with single quotes.

Strange though it may seem, this functionality can actually be very useful, as it tends to be a lesser evil than using macro quoting functions. Woe betide you should you accidentally try this with an odd number of double quotes, though...

Length 10

%quote(%()

Loosely speaking, the macro processor resolves anything that looks like a macro call (i.e. with a preceding % sign) during compilation, and makes another pass during execution for anything that turns out to be a macro function or variable. Sometimes you need to mask characters that would normally be parsed as macro tokens, or which would otherwise affect compilation. This is one of the most fiddly aspects of SAS.

Depending on precisely what you want to do, SAS has about a dozen different macro quoting functions to choose from, which all behave slightly differently. %quote masks macro characters during macro execution. As demonstrated here, you can also use % characters within certain macro quoting functions to tell the macro processor not to expect a balancing quote or bracket.

Length 11

if first.a;

This is a common data step use case of by-group processing - one of the most distinctive features of SAS. When you use a by statement, SAS uses a system of input buffers to keep track of whether any of the by variables have changed value between iterations. E.g. to use the above snippet, you would need something like by a; first in your data step. Usually, this needs the dataset to be sorted in ascending order.

This snippet is equivalent to if not(first.a) then delete; which under most circumstances means if the current value of a appeared in a previous row, stop this iteration of the data step and don't output the current row.

Length 12

*";*';*);*/;

One of the joys of the SAS Enhanced Editor window - the setting in which one can run SAS code interactively - is that it is quite easy to accidentally submit an incomplete fragment of code for processing. When this happens, SAS will often appear to have stopped responding, usually because it thinks you've left a comment, bracket or quoted string open and is waiting patiently for you to close it. This snippet is an example of a 'magic string' that when submitted enough times may enable you to regain control of your session. Or not.

Length 13

data a/debug;

One largely forgotten component of SAS is the interactive data step debugger. This functions in a similar manner to the MS Office Visual Basic Editor, allowing you to execute iterations of a data step one line at a time and check the values of variables at each point. However, due to the amount of keyboard input required to operate the debugger once you've launched it, it's usually quicker just to modify your data step code so that it prints the equivalent diagnostic information directly to the SAS log.

Length 14

array a{2}(1);

In SAS, arrays are very transient things - merely a way to pick variables from a list numerically rather than by name for the duration of a data step. Once it finishes executing, the variables may still be present somewhere, but the array is gone.

When called in a data step, this snippet creates a numeric array called a containing two elements, which are auto-named a1 and a2. a1 is initialised (to 1) but a2 is not and takes the missing value ..The elements can be referred to as a[i], where i is a numeric variable or constant. Values of the array variables are retained across observations. The elements of a can be referred to as a[i], where i is a numeric variable or constant.

The second set of brackets are required to be round brackets (), but the first set can be replaced with square brackets [] or braces {}. Similarly, you can use any of these when referring to array elements in code.

Length 15

a='01jan1960'd;

We finally have enough characters to show an example of using a SAS date literal. The SAS date epoch is 1st January 1960, so this snippet is equivalent to a=0;. The core SAS language has no concept of data types beyond character and numeric, so even though we've used a date literal there's no way to distinguish between the raw output of these two statements. It's important to note that literals don't behave the same way in the macro language - if you ran something like %let a='01jan1960'd; then the resulting macro variable would be treated as a string until it was evaluated within a core language statement or function.

Length 16

where a=*"John";

Compared to some other languages, SAS has a modest set of operators (perhaps unsurprisingly, given the limited number of types). However, SAS still found space to include one for SOUNDEX matching. When included in a data step or proc, this line restricts the input to records where the variable a sounds like John - e.g. Jane would match. Unlike most other SAS operators, the sounds-like operator is only valid in where clauses, not in more general expressions.

Length 18

input a is8601dt.;

One of the strongest features of SAS is its ability to read data stored in practically any imaginable format with a relatively modest amount of code. The input statement has quite a complex syntax and can be challenging to use, but offers the greatest flexibility when reading in external data out of all the available methods in SAS.

The snippet above uses the built-in is8601dt. datetime informat to read in text of the form YYYY-MM-DDThh:mm:ss from the start of each line of an input file and store it as a numeric SAS datetime variable a. E.g. the text 2014-12-31T23:59:59 would be stored as 1735689599 - the number of seconds since 1st January 1960.

Length 19

proc means noprint;

One curious historical quirk of SAS is that it has ended up with two procs that calculate summary statistics for datasets, with near-identical features and syntax - proc means and proc summary. In early versions of SAS these were distinct procs, but over the decades they've converged to the point where they now share a help page. This example highlights one of the few remaining differences - proc means will output to the listing area by default, unless as here you tell it not to, whereas proc summary doesn't. Although this is a valid SAS statement, it is not a complete call to the proc - at a bare minimum, to request default statistics for the last used dataset, you would need to add a run; afterwards.

Length 20

data a(index=(var));

Another strength of SAS is its ability to crunch through vast volumes of data on disk, without requiring similarly vast amounts of memory - this has historically been one of the main advantages of SAS over R, though in recent years R has been catching up. As with other DBMS software, indexes help tremendously when you only need to extract a small proportion of records. This statement tells SAS to index the variable var when creating the dataset a.

When working with particularly huge datasets, normal SAS indexes can prove inadequate due to their rather generalised design - as a result, people have developed their own more specialised ones.

Length 21

%macro a(b,c=);%mend;

We now have enough characters available to define a trivial macro. In SAS a macro is simply a way of generating text, which is then interpreted as if it were non-macro code. Eventually, anyway - sometimes multiple passes are required to resolve all macro tokens.

Our macro could called like so:

%a(1,c=2);

This would create two local macro variables, with values b=1 and c=2, and then exit, generating no further code. In SAS-speak, b is a positional parameter of %a, and c is a keyword parameter. Positional parameters, when specified, must always go before keyword parameters (and in the correct order) when calling a macro, unless you refer to them by name. E.g.

%a(c=2, b=1); /*Assigns both values as expected*/
%a(c=2);      /*Sets &b to an empty string*/
%a(c=2, 1);   /*Throws an error*/

Length 22

%let a=a;%put &a.&&&a;

This is a highly circuitous method of printing the text aa to the SAS log. The initial %put &a is straightforward enough- this simply resolves &a to its value a. The . tells SAS that it has reached the end of the name of the macro variable, and is not printed. What happens with &&&a is more complex. In the first pass through the code, the macro processor resolves &a to a, its assigned value, and resolves && to &. In the second pass, the macro processor sees only &a and resolves this to a, which is then appended to the a from earlier and printed to the log. If you need to go several layers of variables in, the number of & signs required increases exponentially.

Length 23

proc datasets lib=work;

This has been described as the 'Swiss Army Knife of SAS procs', and with good reason. As well as listing, copying, appending, deleting and renaming SAS files (including, but not limited to, datasets), it can also be used to make all sorts of changes to the metadata within SAS datasets - things like variable names, formats and so on - without having to run a wasteful data step that overwrites the whole dataset. It is among the minority of procs that allow multiple run; groups (as mentioned in example 5), and requires a final quit; statement after the last one. This modest example lists the contents of the temporary work library.

Length 24

dcl hash h(dataset:'a');

Hash objects were first made available in SAS 9.1. The above statement, when run in a data step, declares and instantiates a hash object h containing variables from the dataset a. This is cheating slightly, as some additional statements are required to declare the key variable(s) you want to use to store/retrieve items in the hash, and optionally some data variables associated with each combination of keys. The most common use of hash objects is for merging small datasets onto much larger ones, as using a hash lookup to retrieve values from a small dataset avoids having to sort the other (much larger) dataset.

Length 25

proc format cntlin=a;run;

Before we had hash objects, the next best thing was a format merge. This worked by defining a custom format to translate lookup keys to lookup values, effectively resulting in the lookup dataset being loaded into memory. This snippet takes a specially structured dataset a and uses it to define one or more formats.

Format merges can outperform hash merges if you only need to look up one variable from your lookup dataset, but they have some limitations. A format can only be applied to one variable, so if your lookup depends on a combination of keys, you have to concatenate them - a messy process. Each key can then only be mapped to one value per format, so if you have multiple lookup variables you end up having to load the keys from the lookup dataset into memory multiple times - distinctly sub-optimal for larger lookup datasets.

\$\endgroup\$
11
  • 1
    \$\begingroup\$ I've been a SAS programmer by title for quite a while now and this is the first time I've seen link. Interesting. \$\endgroup\$
    – Alex A.
    Commented Jan 20, 2015 at 15:36
  • \$\begingroup\$ In my defence, I've never actually used it. \$\endgroup\$
    – user3490
    Commented Jan 20, 2015 at 16:16
  • 1
    \$\begingroup\$ Nice. Hopefully we get a few more votes so the more fun bits of SAS can be explained. I was pleasantly surprised to find this on the first page :) One fun factoid from me: someone wrote a fully functional (ie, playable) Wolfenstein 3D emulator in SAS a decade or so ago. \$\endgroup\$
    – Joe
    Commented Jan 27, 2015 at 23:00
  • 1
    \$\begingroup\$ @user3490: It's useful to note that SAS has no concept of data types beyond character and numeric, except in the DS2 and FedSQL procedures, which feature multiple data types. \$\endgroup\$
    – Alex A.
    Commented Jan 28, 2015 at 21:20
  • 1
    \$\begingroup\$ @Alex wolfensas.subshock.net . I'm not sure how well it behaves on newer machines/etc., but it used to work at least... it uses SAS to talk to DirectX, I believe. \$\endgroup\$
    – Joe
    Commented Jan 28, 2015 at 21:33
30
\$\begingroup\$

Perl

Factoid: Though people occasionally stylize Perl as "PERL," it is in fact not an acronym.

Note: This has been relinquished to the community as a wiki. Please feel free to add snippets as you see fit, but please try to retain the formatting used for snippets 1-6 since it looks so clean. :)


Length 27

sub{ $_=shift; lc }->('SE')

An anonymous subroutine: that is, one with no name. This one is followed immediately by ->(...) for its arguments. This snippet also demonstrates a number of other features:

(1) shift acts on an array, lopping off the initial element and returning it; (2) @_ is the array holding all the arguments passed to a subroutine; (3) shift with no arguments, in a subroutine, acts on @_. Thus, the first statement in our subroutine assigns to the variable $_ the first argument passed to the subroutine, in this case 'SE'.

(4) lc returns the lowercasified version of a string (without changing the original variable if the argument is a variable); (5) lc with no arguments acts on $_. Thus, here, lc acts on $_ which is 'SE' and returns 'se'.

(6) If you reach the end of a subroutine (and thus haven't yet returned anything), the subroutine returns the return value of its last statement, if any. Thus, in this case, the subroutine returns 'se'.

Note: Many of these features are very useful in code golf; in real life, for clarity's sake, you will often want to specify the arguments to functions rather than relying on default arguments like $_, and to specify return values of subroutines rather than relying on the return value of the last statement (especially if the last statement is complex).


Length 26

join '', split /\W/, $foo;

This demonstrates using a function (with its arguments, or a unary operator) as an argument to another function or unary operator. When, as here, the first function is the final parameter of the other, you usually don't need parentheses to disambiguate. They may be useful for clarity in some cases, but the join... split... construct is so well-known that you don't need parentheses here.

split takes two arguments. (Well, it can take zero to three, but it takes two in this case.) It splits the string $foo along demarcations matching the regular expression /\W/, and its return value is a list of the remaining substrings. join puts those back together with the empty string between them. (Incidentally, $foo =~ s/\W//g is a simpler way to accomplish the same thing.)


Length 25

sub foo {
    return 1;
}

Our first subroutine! In a later snippet, we'll see how to use arguments (parameters) passed to a subroutine; for now, our subroutine just returns 1 back to whatever called it. Our subroutine is called foo; anonymous subroutines are also possible and will be covered in a later snippet.


Length 24

my $has_nums = $x=~/\d+/

See the length-23 snippet. Like that one, this, too, binds $x to a regular expression, and almost the same one. (Like /(\d+)/, it looks for a string of digits.) But this one is being assigned to $has_nums rather than to a list, so it's being called in scalar context. The binding operator =~ in scalar context, when the right-hand side is /.../, returns 1 (which is true) or the empty string (which is false) depending on whether the match succeeds. So now you can use $has_nums in if $has_nums, for example. (What =~ returns in scalar context is different if its right-hand side is s/.../.../ or some other things.)


Length 23

my ($num) = $x=~/(\d+)/

This demonstrates =~, called the binding operator. It binds (in this case) $x to the regular expression /(\d+)/. Like just about everything in Perl, this operator returns something, and what it returns depends on what context it's called in. Assigning the binding operator's return to a list ($num) is calling it in list context. The binding operator in list context, when it's binding to just a regular expression /.../, returns the list of matches to the stuff in parentheses in the regular expression, which in this case is \d+, a string of digits. So $num is assigned to the first string of digits within $x. (What =~ returns in list context is different if its right-hand side is /.../g or s/.../.../ or other things.) See also the length-24 snippet.


Length 22

$x = 1==0 ? 'a' : 'b';

... ? ... : ... is the ternary operator. It has precedence over comparison operators like == but not over assignment operators like =, so the above means the same as $x = ( (1==0) ? 'a' : 'b').


Length 21

if ($x) {
    # ...
}

This demonstrates Perl comments, which are from # to the end of the line, and the common practice of indenting four spaces for clarity. (There are other ways to comment, too, but those will have to wait for a later snippet. This snippet also tests $x for truthiness, but truthiness, too, will have to wait.)


Length 20

next LBL if $x >= 0;

This demonstrates Perl's use of postfix if. (It means the same as if ($x >= 0) {next LBL;}.) Postfix control-flow statements are usually (outside of golfing) reserved for things like next and last and warn and die where the point of postfixing is to draw attention to the crucial command being conditionally executed.


Length 19

$_ = 'quux';
print;

This demonstrates Perl's use of a default input for (many) built-in functions. If you don't say what you want to print (or lcfirst or sqrt or split or…), Perl will do it to $_. (The same is true for binding to a pattern match, and $_ is the default scalar used in other circumstances also — but those will have to wait for a later snippet.) For clarity and to ensure you're using the variable you think you're using, it's often best to use some variable other than $_.


Length 18

@hsh{'Ann', 'Bob'}

This is a hash slice. As in the Length 17 note, below, the {...} (rather than [...]) signifies that %hsh is a hash. And the @ sigil here signifies we're making a list of our hash values. Which hash values? The ones with the keys listed. So if %hsh is ('Ann' => 123, 'Bob' => 345, 'Cam' => 567) then @hsh{'Ann', 'Bob'} is (123, 345).


Length 17

$ary[0] = $hsh{a}

$ is the sigil for a scalar. But an element of an array, or a value of a hash, is a scalar. So even though may call an array @ary and a hash %hsh, their values are $ary[...] and $hsh{...}. The type of bracket indicates whether it's an array or a hash.


Length 10

print$x=<>

This is a “one-line cat” program: it outputs one line of its input, then exits. It demonstrates several features of the language. The null filehandle is used again, now to assign a line of input to the variable $x. This assignment also returns the value, which is then printed to STDOUT. But wait! Didn't <> return the whole file in Snippet 7, not just one line? Perl statements know about the “context” they're evaluated in. In “scalar context”, <> reads one line. In “list context” it reads (“slurps”) the whole file at once; the result is a list with one element for each line. print provides a list context (and concatenates its argument list), but assignment to the scalar variable $x enforces scalar context.


Length 7:

print<>

This, like cat, prints back its input. The <> is the “null filehandle”; its lack of a name means that it reads from the “magical” filehandle ARGV, which sequentially opens and reads from filenames given as line arguments, or STDIN if there are no arguments (just like cat does). In the full form, the filehandle goes between the angle brackets: <FILEHANDLE> may also be spelled readline(*FILEHANDLE).


Length 6:

Int $x

Perl 5 is all dynamic typing. But Perl 6 supports both static and dynamic typing! It's one of the many ways in which the two versions have diverged.


Length 5:

'$x'

This may seem trivial but it's something that can confuse people new to Perl who are familiar with other languages. In some languages, it doesn't matter whether you use single or double quotes. It does in Perl, though. If you have a variable $x equal to 5, "$x" returns "5" and '$x' returns '$x'. Perl interprets things in double quotes but uses anything in single quotes literally.


Length 4:

less

The Perl pragma to use less of something, available in CPAN. Examples include use less 'fat'; for those on a diet, or use less 'CPU'; for those whose computers are on diets. The class method less->of('x') will tell you if use less 'x'; was specified. Unless you take advantage of that class method in some way, specifying use less is useless. (See what I did there?)


Length 3:

use

Perl is extensible via modules, which are loaded using use. Other things use use too. Show self-discipline; use strict; use warnings; in your programs.


Length 2:

$!

Oh no, something has gone wrong! The program has died, be it intentionally (via die) or by the will of Zeus. But why oh why has execution stopped? At last, $! rides the Perl camel to the rescue. It contains the error code. (There's also $@, which contains the error message.)


Length 1:

;

Like so many other 1 character answers here, ; is a valid Perl statement which does nothing. On its own it's about as useful as vacuuming a block of tofu.

\$\endgroup\$
6
  • \$\begingroup\$ It seems snippet 10 isn't really a cat. With perl 5.18, at least, it prints only one line. To echo all the input, one could write e.g. print(<>); (which is ten characters long) or print $x=<> until eof (which is slightly smarter). \$\endgroup\$
    – xebtl
    Commented May 11, 2015 at 19:56
  • \$\begingroup\$ @xebtl: I think it was PhiNotPi who did snippet 10. I made this a community wiki so go ahead and make changes as you see fit. :) \$\endgroup\$
    – Alex A.
    Commented May 11, 2015 at 20:07
  • \$\begingroup\$ How about this? If it is too repetitive, we can delete Snippet 7 again. Perl is so full of features worth showcasing! \$\endgroup\$
    – xebtl
    Commented May 11, 2015 at 21:02
  • \$\begingroup\$ @xebtl: Looks good to me. Note that some features not covered here may already be covered by ASCIIThenANSI's Perl submission. \$\endgroup\$
    – Alex A.
    Commented May 11, 2015 at 21:04
  • \$\begingroup\$ @ASCIIThenANSI: If you have more to share that you didn't cover in your Perl answer, you're welcome to contribute to this community wiki. \$\endgroup\$
    – Alex A.
    Commented May 11, 2015 at 23:30
29
\$\begingroup\$

F#

F# is a strongly typed, multi-paradigm programming language that encompasses functional, imperative, and object-oriented programming techniques.

All the snippets included here can be run online at: http://www.tryfsharp.org/Learn (exception: FSI snippet).

Length 9 Snippet

(10, "Z")

Tuples! a Tuple is defined as a comma separated collection of values. While Lists (and Arrays) gravitate towards the concept of a Set, Tuples are more like a data structure that groups related values.

The snippet defines a 2-tuple. One value is integer, the other string. F# annotates the type as: int * string

Tuples are considered ad hoc types, so they are passed as a single argument, can be a return type and so on.

F# has two built in functions to help with tuples: fst and snd that return the first or second element of a Tuple respectively. Tuples are not limited to just two elements, though.

Length 8 Snippet

[-9..10]

F# allows to define ranges of sequential values. This snippet generates a list of 20 integer elements, -9 and 10 inclusive.

You can define stepping values, for example [0..10..50] will yield a list of 6 elements: [0; 10; 20; 30; 40; 50].

The range syntax is the same for lists and arrays.

Length 7 Snippet

let a=1

We can now define values. Values in F# are immutable by default, that is the reason we avoid the use of the term "variable".

The snippet defines an immutable value "a" that contains a 1 (integer).

Length 6 Snippet

2.**8.

Now we can use the Power function.

Note that I could not call the Power function before with arguments "2" and "8", because [the arguments] would be considered integers. The decimal points make the compiler to infer a floating point number. This snippet correctly returns a 256.0 (float) value.

Floats in F# are double precision.

Length 5 Snippet

[|0|]

At five characters, we can define an array with one element (as mentioned before, the compiler infers the type to int[]).

Not to be confused with a list. An empty list is defined simply by the square brackets like this: []

The element separator, in both lists and arrays, is the semicolon (;) as in [| 1;2;3 |]

Length 4 Snippet

(**)

It's not an emoticon, it is a multi-line comment in F#. For some odd reason I didn't find this syntax intuitive. I got used to it until much later.

Single-line comments are double-slash (//), just like C++, C#, Java, etc.

Length 3 Snippet

nan

Three characters unlocks many basic arithmetic operations (1+2, 9*9 and so on). But I picked nan. It is a shortcut function that simply returns System.Double.NaN.

Useful to compare (or match) the result of a function.

Length 2 Snippet

;;

I could've used an empty string ("") as the snippet. That would create a function that returns an empty string, but it is the same concept as the length 1 snippet.

Instead, I picked the empty statement in F# Interactive (FSI). FSI is a REPL tool that allows you to declare, construct and otherwise experiment with your code in an interactive manner and it is very useful. In my opinion, the ;; is used more frequently than empty strings.

You must append double semicolons (;;) at the end of your statements in FSI to indicate the end of input.

Length 1 Snippet

0

A function that returns zero (the compiler infers the type to integer). Commonly used as the final statement to return the program exit code.

Factoid: F# uses type inference. The programmer does not need to declare types - the compiler deduces types during compilation.

\$\endgroup\$
1
  • \$\begingroup\$ Just FYI: Mathematica has the same syntax for multiline comments so it's not all that foreign. :) \$\endgroup\$
    – Alex A.
    Commented Apr 6, 2015 at 21:28
29
\$\begingroup\$

PHP

PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. As of January 2013, PHP was installed on more than 240 million websites (39% of those sampled) and 2.1 million web servers. Originally created by Rasmus Lerdorf in 1994, the reference implementation of PHP (powered by the Zend Engine) is now produced by The PHP Group. While PHP originally stood for Personal Home Page, it now stands for PHP: Hypertext Preprocessor, which is a recursive backronym.

Link for myself, or anyone who wants to contribute to this answer.

Length 16

The function

http_build_query

builds a query string for an URI from an associative array.
One of many functions that´s closely connected to web development.

Length 15

array_intersect

This function returns the common elements of two or more arrays.

Array function names in PHP are bulky. Apart from implode and explode (respectively join and split), they are almost always prefixed.

Length 14

imagefilledarc

Since version 4.0.6, php has builtin image processing with some pretty sophisticated functions. imagefilledarc is one of them. It can be used e.g. for painting a three dimensional pie chart.

Length 13

if($a >= $b):

This is the alternative syntax for control structures, which ends when it finds a endif; statement. This syntax can be used with if, while, for, foreach, and switch, and end with endif; endwhile; endfor; endforeach; or endswitch; respectively. This alternative syntax is most used to output html without echoing html tags:

<?php foreach($items as $item): ?>
<p><?php echo $item; ?></p>
<?php endforeach; ?>

Length 12

function(){}

This is an example of anonymous function, that can be assigned to a variable, or passed as parameter, for example:

$cmp = function($a,$b) {
  if($a<$b) return -1;
  if($a>$b) return 1;
  return 0;
};
$arr = array(3,1,2);
usort($arr,$cmp);
print_r($arr); // array( [0] => 1, [1] => 2, [2] => 3 )

Length 11

['a'=>[12]]

This statement is equal to array('a'=>array(12)), this short array syntax available since PHP 5.4.

Length 10

$a=array()

This is an example on how to create an array, don't forget to add ; at the end of the statement. The array will have empty length, you can check it using sizeof function. To append at the end of that array, you might use []= operator, for example: $a[] = 12, this would append a number 12 to that array, that similar as typing array(12) at initialization.

Length 9

phpinfo()

This function will print all information about current configuration and variables on your system.

Length 8

__FILE__

Magic constant __FILE__ is a constant that have different value depends on the file its being declared, there are also __LINE__ that shows the line number where its being declared, and __FUNCTION__ for function, __DIR__ for directories (since PHP 5.3). You could see the full list here. They could be used as better way to implement includes, for example: include dirname(__FILE__).'/file.php'; or include __DIR__.'/file.php';, credits: @ismael-miguel

Length 7

4**3**2

Exponentiation operator ** is supported since PHP 5.6, the result of that execution is 262144 (from 4**9)

Length 6

$_POST

This is a global variable that holds value from HTTP protocol with method POST, for example, if you have this form: <form method='post'><input type='submit' name='a' value='b' /></form>', when that button clicked, the current PHP script could access the submitted value using $_POST['a'] that would equal to 'b' string.

Length 5

<?=5?>

This is an example to write number 5 to output, this statement equal to <?php echo 5; ?>, don't forget to enable short_open_tag in your php.ini to enable this feature.

Length 4

NULL

NULL is a constant that holds the value of any variable that hasn't been set yet, or have been unset, or any variable/constant that has been assigned as NULL.

Length 3

1.2

This is example on how to create a float type value. Do not compare float values with equality == operator since they are imprecise. To check whether a variable is a float type, use is_float function.

Length 2

''

This is how you create an empty string in PHP, there are other way such as double quote "". For performance reason, always use single quote unless there are interpolation.

Length 1

a

Anything that written outside <? or <?php and ?> are treated as output, so, if a .php file containing only a character a, that character itself would be the output.

Factoid

Some of the biggest online sites, such as Facebook, Wikipedia, and Yahoo! are powered by PHP.

\$\endgroup\$
10
  • 1
    \$\begingroup\$ 7 byte snippet: array() or $s?1:0;. \$\endgroup\$ Commented Jan 23, 2015 at 15:22
  • 2
    \$\begingroup\$ 8 byte snippet: <?=text; (it shows that you don't need the closing tag (useful for included files that aren't meant to produce output) and it shows that undefined constants are converted to strings (but raise a warning when doing so)). \$\endgroup\$ Commented Jan 23, 2015 at 15:27
  • 1
    \$\begingroup\$ When you get a lot more of upvotes, you can use this one: <script language="php"> which is a valid opening tag. (Doc: php.net/manual/en/language.basic-syntax.phpmode.php) \$\endgroup\$ Commented Jan 23, 2015 at 15:35
  • 1
    \$\begingroup\$ I got surprised when I found it, almost 1 year and a half ago. And you should specify that the constant __DIR__ is only available in PHP 5.3 and up. Also, a better way to implement includes is to use include dirname(__FILE__).'/file.php'; or include __DIR__.'/file.php'; which increase the performance by reducing a few filesystem lookups for relative paths. \$\endgroup\$ Commented Jan 23, 2015 at 16:42
  • 1
    \$\begingroup\$ Also, a 0 byte snippet is an empty file being accessed with ?=PHPE9568F34-D428-11d2-A769-00AA001ACF42 at the end (e.g.: localhost/index.php?=PHPE9568F34-D428-11d2-A769-00AA001ACF42). It should display PHP's logo. \$\endgroup\$ Commented Jan 24, 2015 at 2:35
29
\$\begingroup\$

LOLCODE

Note: I will be following previous rules of this showcase before mods stepped in, in that the length of my longest snippet will be equal to the number of votes this post has.


25 characters

HAI 1.3
VISIBLE 1
KTHXBYE

This is a complete program that prints 1 to the standard output.

24 characters

HOW IS I z
3
IF U SAY SO

Defines a function z that when called, returns 3.

23 characters

VISIBLE SUM OF a AN 32

Prints variable a plus 32.

22 characters

I HAS A var
GIMMEH var

Create a variable and assign input to it.

21 characters

VISIBLE “HAI WURLDZ!”

The LOLCODE Hello World Program!!! w00t w00t!

20 characters

I HAS A big ITZ FAIL

Creates a variable big and assigns it to FAIL, the falsy boolean.

19 characters

QUOSHUNT OF 99 AN 9

Returns 11, 99 divided by 9.

18 characters

I HAS A var ITZ 99

Creates variable var and assigns it the value 99, a NUMBR.

17 characters

O RLY?
YA RLY
OIC

Similar to the last snippet, this is a blank if statement. O RLY? takes the value in IT and tests it for truthiness. If true, it runs the code in the YA RLY block, then exits at OIC.

16 characters

WTF?
OMGWTF
OIC

A switch/case statement. Takes the variable in IT (the runtime temporary variable) and matches it up with any OMG <value> statements. Since there are none, it goes right to OMGWTF, the default statement. Since there is no code in the block, it goes right to OIC and continues with the code.

15 characters

HAI 1.3
KTHXBYE

The shortest complete program. All LOLCODE programs start with a version number and end with KTHXBYE.

14 characters

DIFF OF 9 AN 6

Returns the difference of 9 and 6

13 characters

CAN HAS TIME?

Imports the library TIME if it exists.

12 characters

GIMMEH INPTZ

Gets input from STDIN and saves it to the already-defined variable INPTZ.

11 characters

OBTW
C
TLDR

A multi-line comment (C is the content)

10 charaters

VISIBLE 10

Prints 10 to STDOUT.

9 characters

I HAS A Z

Creates a variable called Z.

8 characters

VISIBLE 

(note the trailing space) Prints… nothing.

7 characters

HAI 1.3

The hello() of LOLCODE.

6 characters

GIMMEH

A function asking for input from STDIN. This does nothing as it's not assigned to a variable though.

5 characters

Y R 6

Assigns the NUMBR 6 to the already-defined variable Y

4 characters

":)"

A newline inside a YARN. THE : character is the escape character inside strings.

3 characters

BTW

An empty comment. w00t.

2 characters

""

An empty YARN

1 character

I cantz do real stuff with my 1 char!!

-- Hohmannfan

3

It da NUMBR 3.

Factoid

Is composed almost completely with Internet slang.

\$\endgroup\$
6
  • 4
    \$\begingroup\$ 1 character: "I cantz do real stuff with my 1 char!!" \$\endgroup\$ Commented Apr 14, 2016 at 22:27
  • 1
    \$\begingroup\$ yah me cantz ur rite \$\endgroup\$
    – AAM111
    Commented Apr 14, 2016 at 22:55
  • 1
    \$\begingroup\$ CAN I HAZ LENGTH 10? sorry for shouting :3 \$\endgroup\$
    – fede s.
    Commented Apr 25, 2016 at 2:15
  • 1
    \$\begingroup\$ YA U CAN HAZ LENF 10 \$\endgroup\$
    – AAM111
    Commented Apr 25, 2016 at 21:18
  • 1
    \$\begingroup\$ I HAZ A VAR; VAR R 12; CAN HAZ LENF R?!!??!?!; GIMMEH! \$\endgroup\$
    – cat
    Commented Apr 28, 2016 at 2:34
28
\$\begingroup\$

OpenSCAD

OpenSCAD is a language used to create parametric and accurate 3d models using nothing but code. Note: I refer to CSG multiple times in this post; this stands for Constructive Solid Geometry. This means constructing a model through a combination of combining objects, subtracting objects, and intersecting objects.

Factoid:

Since a .scad file is plain text, it occupies very little space, and you can use tools like diff effectively.

Length 1:

Well, there isn't too much you can do with one character, but one very useful character is the debug modifier:

#

This character can be placed in front of any CSG tree to highlight it, even if it would be invisible in the final output (such as if the CSG object was subtracted from another object). I'm not allowed to write any more code to explain this, so I'll use pictures.

Without the modifier:

No modifier

With the modifier:

With modifier

(Image Source: OpenSCAD User Manual, Wikibooks, CC-BY-SA)

Length 2:

In OpenSCAD, you can create simple animations. How, you ask? This is done using a special variable for animation:

$t

This variable repeatedly loops from 0 to 1, which your code can use to change the position of an object, rotate an object, or do pretty much anything when combined with control flow structures. OpenSCAD can dump png frames at user specified intervals to create videos and/or gifs.

Adding a single line of code to a program (in this case, one of the examples, which also happens to be the OpenSCAD logo), and running the output through a gif maker can turn it into an animation like this: Rotating OpenSCAD logo

Length 3:

There are a wealth of libraries in OpenSCAD, and one way to access them is via the command:

use

There are actually two commands with similar functionality, but the other one has too many bytes. The main difference is that any top-level code (code outside a function/module) isn't executed with use, while it is executed for the other command. Both commands must be placed before any use of imported functions.

There are a couple of widely used libraries (Note that some of these should be added to the project with the other command instead):

  • MCAD- this contains basic utilities (more shapes, gears, some math, etc), and often is installed automatically with OpenSCAD.
  • Write.scad- Many of it's functions have been superseded by built-in functions in OpenSCAD, but it allows you to do a little more than the built-in functions can do (write curved text, for example).
  • BOLTS- This extensive library allows you to use standard hardware parts (and some non-standard hardware) in your projects.
  • The General Library of Relativity- Allows creating and positioning of objects relative to other objects.
  • String Theory- Made by the same person as Relativity, this provides various string utilities, along with regex functionality.

Length 4:

4 bytes is in that weird range where you can't really show off special variables or 1-character modifiers, but it's too short to really demonstrate the usage of a keyword.

However, it is the smallest whole program that isn't empty (or made up of only whitespace and semicolons) that compiles/runs without an error:

a=1;

This just assigns 1 to the constant a. In OpenSCAD, almost everything is a constant within its scope. Recursion, iteration, and defining separate constants are two common ways to circumvent this limitation. Note that OpenSCAD is dynamically typed.

Length 5:

Much of OpenSCAD's power comes from its conditional branching. Assuming that a is a boolean value, you can write:

if(a)

Alternatively, you can put in any expression that evaluates to a boolean. This may be followed by a single statement, or by a code block surrounded by braces. The if statement shouldn't be used to conditionally assign variables, however—Any variable re-assignment creates a scope for the new variable which effectively shadows, not replaces the original variable. Conditional variable assignment must be done on declaration of the variable, with the ternary operator.

Length 6:

This one is really cool:

hull()

It's the digital equivalent of wrapping a piece of plastic wrap around an object:

Without hull:

No hull

With hull:

Yes hull

Length 7:

This one isn't too exciting, but it is very useful:

[0:2:6]

This evaluates to an array. The first number is the starting value, the last number is the ending value, and the (optional) middle number is the step. For example, the previous line of code would evaluate to [0,2,4,6]. Arrays can be nested (jagged arrays and different levels of nesting are allowed) and they can be assigned to a variable.

Length 8:

This is one of the three main CSG operations in OpenSCAD:

union(){

Now would be a good time to talk about the tree structures in OpenSCAD. In OpenSCAD, every object (in terms of 3D modeling, not OOP; OpenSCAD is definitely not OOP) is a node on a tree, and each can contain sub-trees.

Every OpenSCAD model is built from a handful of built-in primitive objects (these primarily act as end-nodes), and various built-in operations (these typically contain their own sub-trees). Additionally, you can define your own operations that either transform their sub-trees, or create a model on its own—but that's a topic for later on.

Back to union: this operator wraps everything in its sub-tree into one node (but doesn't do anything to the objects themselves), so that they can be treated as one whole unit when used in other operations. It may not do much on its own, but when combined with other operations, it can be a vital tool.

Length 9:

Here's a mouthful:

minkowski

The minkowski function involves taking the minkowski sum of an object. This one is a bit weird, as it is taking one shape, and moving it around the surface of another object. It's hard to explain in words, so an image is definitely helpful.

Non-summed:

Not summed

Summed:

Summed

The same process can also be extrapolated into the third dimension:

3D Non Summed 3D Summed

Note that when using this, it can take a while for it to render, especially for more complex objects.

Length 10:

Here is another important CSG operation:

difference

This takes the first element of its sub-tree, and "subtracts" every other object in the sub-tree from it.

For example, in this picture, the cylinder is being subtracted from the cube. Note that the debug modifier is used to make the cylinder visible:

Difference

Length 11:

Finally, there are enough bytes to be able to define a module:

module a(){

A module in OpenSCAD can define an object, operate on objects, or both. Everything (including the built-ins) that creates or modifies objects (not numbers, booleans, arrays, or strings, though; those are for functions, which I'll talk about in another section) is a module. The module can also accept variables (and define default values), though you have to be careful, as OpenSCAD is dynamically typed. Some modules can operate on their sub-trees; however, most modules won't do anything if they are passed a sub-tree. More info can be found here.

Length 12:

Finally, the third major CSG operation

intersection

This takes the intersection of two objects.

For example, the intersection of these two objects:

Not Intersected

would be:

Intersected

Note that intersection doesn't work as expected when working with for loops, but there is a way around that. This may to change in future versions, however.

Length 13:

Everything so far has been a yellow (or translucent red) color. How boring! You can spice it up with colors like "mediumspringgreen" and such, but since that would put this over the length limit, I'll choose a different color:

color("cyan")

As expected, this changes the color of its subtree:

It's also "aqua"

The color module accepts any of the standard CSS/SVG color names, and can also accept a vector of RGB colors (scaled from 0-1, not 0-255) with an optional transparency. More info on color here.

Length 14:

OpenSCAD includes the for loop, for simple iteration:

for(i=[0:2:8])

There are a couple finer points when dealing with for loops. For one, the loop variable can iterate over any array. As stated in the Length 7 snippet, [0:2:8] simply evaluates to [0,2,4,6,8] when looped through. Since OpenSCAD isn't type safe, make sure that the loop body can handle the loop effectively. Besides a special for loop for dealing with intersections, there are a couple variations that greatly expand the for loop's capability that I'll describe when there are more bytes.

Length 15:

Adding to the list of built-in modules:

scale([x,y,z]){

(Note that [x,y,z] is a vector, which is basically an array in OpenSCAD. You can substitute the whole expression for a variable that equals a vector.) When applied to a sphere, you can do things like stretch it so it becomes a blimp-like shape:

Blimp

This command can be applied to any sub-tree and have a similar effect.

Length 16:

resize([5,8,10])

This command takes the bounding box of the subtree, and stretches (or shrinks) each axis to fit in a new bounding box. For example, say you have a sphere of radius 10:

Sphere

If you resize it to a 5x8x10 bounding box, it becomes:

Whatever this is

Length 17:

linear_extrude(h)

(where h means height)

If I take this 2D square (size 10x10):

Square

and I apply a linear extrude with a height of 5 to the square, then I get a rectangular prism:

Rectangular prism

Length 18:

While you can't set arrays from inside a for loop (the variable inside the for loop shadows the variable in the wider scope), OpenSCAD compensates by adding list comprehensions.

[for(i=[1:10])i*2]

This list comprehension iterates i from 1 through 10, and for each value of i, the result is 2i. This expression results in the array [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]. Note that this array could have been produced with [2:2:20].

Length 19:

import("model.stl");

(Note that STL is a file format for 3D models. It contains a triangular mesh of all of the surfaces in a model.)

If I save the hilbert cube model from here as model.stl in the same folder as the .scad file, OpenSCAD allows you to use it as a component of the model (e.g. you can perform CSG operations on the model).

Hilbert cube

Length 20:

Let's do some animation!

$vpr= [45,0,$t*360];

$vpr is a special variable in OpenSCAD. It contains the rotation of the viewport ($vpt and $vpd contain the translation and distance, respectively). If you assign them a new value, the viewport changes to that value.

As stated earlier, $t contains a value between 0 and 1.

To start with animation, click View > Animate. That will bring up a bar like this:

Bar

Time will automatically change when you configure the other two values. This becomes the value of $t.

Steps means the amount of steps that $t will go through between 0 and 1.

FPS is the amount of steps OpenSCAD will go through every second.

If "Dump Pictures" is selected, as OpenSCAD goes through the animation, it will save the pictures sequentially.

With the above code, 30 steps, and 10 FPS, I get this exciting animation:

Super exciting

Of course, you can use $t in other places as necessary.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Looks like a very interesting language; I'd love to see more. :) \$\endgroup\$ Commented Oct 8, 2015 at 18:35
  • \$\begingroup\$ I did not expect to see an OpenSCAD answer here, props! \$\endgroup\$
    – cole
    Commented Oct 10, 2015 at 3:59
28
\$\begingroup\$

JavaScript, EcmaScript 6

I will be focusing on features/snippets of/from ES6 standard in this answer. Some snippets require knowledge of topics previously presented, so you may want to read this bottom-to-top.

Length 17 snippet:

"𠮷".codePointAt()

More Unicode support! .codePointAt() is a Unicode-compliant version of .charCodeAt(). For example, if you were to take

"𠮷".charCodeAt()

you would find 55362. This might seem right, but if you convert it to hexadecimal, you would find that it corresponds to U+D842. Looking on Graphemica, we can see that the character is actually U+20BB7. U+D842 is one of the two surrogates that makes up the UTF-16 representation of that character.

But enough of these details: the point of .codePointAt() is to find the actual Unicode point of the character. "𠮷".codePointAt() is 134071, or U+20BB7—the correct result. Finally Unicode lovers can use JavaScript!

Length 16 snippet:

/^.$/u.test("𠮷")

Another nice feature of ES6 is proper Unicode support! If you tried this code in ES5:

alert(/^.$/.test("𠮷"))

You might be surprised to find that the answer is false! The problem here is in JavaScript's default encoding, UTF-16: characters above U+FFFF are actually represented as 2 chars, called "surrogates". (You can learn more about this on Wikipedia.) In order to fix this, you need a more complex regex:

alert(/^(?:[\uD800-\uDBFF][\uDC00-\uDFFF]|.)$/.test("𠮷"))

ES6 introduces the u flag on regexes. When u is set, characters above U+FFFF are still captured as a single char. So /^.$/u.test("𠮷") returns the correct result: true.

Length 15 snippet:

String.raw`q\n`

Back to tagged templates! ES6 comes with a function all set up to be used as a tag: String.raw. This returns the raw text you typed in the template (replacing interpolations with their values), so the above snippet is equalivalent to "q\\n".

Length 14 snippet:

Number.EPSILON

As you may know, JavaScript's numbers are not arbitrary-precision; they have exactly 53 bits of precision. This can cause problems when trying to add decimal numbers:

var point3 = 0.1 + 0.2;
alert(point3 === 0.3); // false!

The problem here is that neither 0.1 nor 0.2 can be represented exactly in binary, and when adding them together, the least significant bit is rounded the wrong way, resulting in 0.30000000000000004 instead of 0.3.

Number.EPSILON was added as a workaround to this problem; it is equal to 2-53, the smallest number that can be added to 1 without rounding back down to 1. We can use this to create a new equals function:

equals = (num1, num2) => Math.abs(num1 - num2) < Number.EPSILON;

alert(equals(point3, 0.3)); // true!

Hooray for ES6!

Length 13 snippet:

s=>s.split` `

What is this? A function call without parentheses? Actually, it's another use of template literals: tagged templates! But what is actually happening here?

When you tag a template with a function, it calls the function as usual, but it passes in the arguments a little differently. Take this example function:

function parseMe(strings, name, age) {
  alert(`Your name is ${ name } and you are ${ age } years old`);
  console.log("We don't need these strings:", strings);
}

myName = "Bob";
myAge = 123;
parseMe `Hello, I'm ${ myName } and I've orbited the earth ${ myAge } times.`;

This alerts Your name is Bob and you are 123 years old. Why? When calling a function with a tagged template, JavaScript passes each ${ } value as a separate parameter, groups the strings into an array which is passed before everything else. So you're really calling parseMe like this:

parseMe( ["Hello, I'm ", " and I've orbited the earth ", "times."], myName, myAge );

Cool, right? Now back to the original snippet. Now we can see that it could be written like this:

s=>s.split([" "])

.split coerces its argument to a string before splitting. The string representation of [" "] is " ", so the function could be written yet another way:

s=>s.split(" ")

And this simply splits the text on spaces, which splits it into words. Isn't ES6 awesome?

Length 12 snippet:

n=>`Hi
${n}`

Introducing...template literals! Yet another super-helpful ES6 feature. These act like strings for the most part, but you can include newlines without escaping them. Not only that, but you can also use interpolation! If you run the above function with input "JavaScript", it will output this:

Hi
JavaScript

Length 11 snippet:

[a,b]=[b,a]

Tired of using that old var tmp = a; a = b; b = tmp; trick to swap variables? Now you don't have to! Using destructuring, you can swap those two variables quickly and concisely with the above statement.

Length 10 snippet:

[a,...b]=b

Destructuring! Yay! This is one of the cooler features of ES6. You can use it to do many things that would have taken a lot more bytes in ES5. For example, this is what the above statement corresponds to in ES5:

a=b[0],b=b.slice(1)

Actually, a=b.unshift() works too, but consider when you want to grab the first three items:

[x,y,z,...b]=b
x=b.unshift(),y=b.unshift(),z=b.unshift()

Or if you don't want to change the value of b:

[x,y,z]=b
x=b[0],y=b[1],z=b[2]

As you can see, destructuring is shorter, more readable, and just all-around better.

Length 9 snippet:

new Set()

Another useful data-type that JavaScript now supports is Sets! You can create a set like so:

var myArray = [1, 3, 6, 3, 2, 1];
var mySet = new Set(myArray);
// Set [ 1, 3, 6, 2 ]

As you can see, creating a Set out of an array removes all duplicate items. You can turn it back into an array with the spread operator:

myArray = [...mySet];
// [ 1, 3, 6, 2 ]

You can also use this trick on strings:

var myString = "Hello, World!";
var mySet = new Set(myString);
myString = [...mySet].join("");
// "Helo, Wrd!"

Keep in mind that the Set constructor must be called with new, and only works on the first argument. For example, this won't work:

var mySet = new Set(1, 3, 6, 3, 2, 1);
// TypeError: 1 is not iterable

You can learn all about Sets on this page.

Length 8 snippet:

(i=0)=>i

You probably understand what this example is: default parameters! JavaScript ES5 is really horrible with default values. Usually you can get away with this workaround:

function f(i) {
  i = i || 0;
  return i;
}

However, this resets i if it is anything falsy (false, 0, "", null, or undefined). To just do null or undefined, you have to be much more verbose:

function f(i) {
  if (typeof i === "undefined" || i === null)
    i = 0;
  return i;
}

But ES6 contains a new syntax for default values! Now you can shorten your code to this:

function f(i = 0) {
  return i;
}

Or in ES6 arrow notation, f=(i=0)=>i. When given an input, this just returns the input, but when called with no input, it returns 0. This is very helpful in uncountable scenarios, and possibly one of the best additions of ES6.

Length 6 snippet:

Symbol

JavaScript now supports Symbols! A symbol is created with Symbol("foo"), and every symbol created is different: Symbol("foo") !== Symbol("foo") The only way to keep a symbol is to assign it to a variable: var sym = Symbol("foo"); sym === sym

One of the most useful Symbols is Symbol.iterator. This is a Generator which is used whenever you iterate over an object, whether with for-in loops or the ... operator (see below). For example, the following code defines an iterator for all Number objects:

Number.prototype[Symbol.iterator] = function* () {
    for(var i = 0; i < this; i++)
        yield i;
}

Now [...6] returns [0,1,2,3,4,5]! Aren't generators fun?

Length 5 snippet:

const

This for a change is exactly what you've guessed! Its a new variable declaration syntax used for creating constant variables.

const a = "foo";

Now a's value is fixed, any attempt to change it will lead to a SyntaxError (cos JS!). Not only that, if you skip the assignment part while declaring the variable, that will also lead to a SyntaxError.

const a;
// Exception: SyntaxError: missing = in const declaration

const a = "foo";
a = "bar";
// Exception: SyntaxError: invalid assignment to const a

Length 3 snippet:

...

Default arguments ? Java ? Nope! This is the new spread operator and it does exactly what it says.

For instance, you want to spread your array variable A into another array B in the middle alongside other things:

var B = [1, 2, 5, ...A, 8, 0];

That simple!

You can even do this with function calls or arguments.

function foo(a, b, ...c) {}

is a function whose first argument goes in a, second goes in b and rest all arguments (third, fourth ...) go in as an array in c.

Now if you want to call that function and all your arguments are in the array A, you can do it like

foo(...A);

Length 2 snippet:

=>

Think that I put greater than or equal to sign the wrong way ? Think again! Think ES6!

This is one of the best features of ES6 - Fat arrow function . Apart from reducing a lot of bytes while defining a function (var a=_=>_+_ instead of var a = function(_){return _+_}), arrow functions also change the behavior of this so that you don't have to bind the function again and again.

Length 1 snippet:

*

Multiplication ? Nope! Remember ES6! The * keywords is part of one of many syntax sugar + features of ES6 - Generators. This is added to the function keyword to make the function a generator function.

Factoid

ES6 adds a lot of useful syntax sugar and features into the language inspired by a lot of other languages.

The most useful fact about ES6 is that due to the added syntax and features, it performs much better than ES5 (current generation JS across all browsers) in terms of .

The final spec for ES6 was finalized in June 2015, and all major browsers (except IE) have enabled most of the new features. You can check this page to see which features your browser supports, as well as all major browsers and other environments.

\$\endgroup\$
8
  • 2
    \$\begingroup\$ I can't wait till ES6 is usable in production \$\endgroup\$
    – DanielST
    Commented Feb 5, 2015 at 21:11
  • \$\begingroup\$ Nice showcase of the new features! Could you add a few more, please? :-) \$\endgroup\$ Commented Sep 30, 2015 at 4:09
  • \$\begingroup\$ Sure, I'll try to update today or tomorrow. \$\endgroup\$
    – Optimizer
    Commented Sep 30, 2015 at 4:14
  • 1
    \$\begingroup\$ ^‌‌‌‌‌‌‌‌‌‌‌ ;) \$\endgroup\$ Commented Nov 29, 2015 at 4:21
  • 2
    \$\begingroup\$ Well, this answer now has 18 upvotes, could you update it? \$\endgroup\$ Commented Apr 11, 2016 at 18:50
27
\$\begingroup\$

Agda

Factoid:

Agda is a Haskell inspired language with even more advanced type system, that makes it possible to declare statements about programs and proof their validity. It comes with proof assistant tools, embedded into Emacs, so you can use it interactively to construct mathematical proofs.

1

_

Underscore has bunch of meanings in Agda. It can mean a wildcard, meaning you don't care about naming stuff when you pattern match. It can tell Agda to guess values or types, which it does by solving type equations. Or as a placeholder in function definitions, it can be placed nearly anywhere, so that definition of post,pre,infix operators are possible (e.g. _! can define factorial and if_then_else_ a condition clause).

2

()

An absurd pattern. Doing a pattern match on an absurd pattern tells Agda, that this pattern is impossible. Or in other words, we trying to match to an empty type (bottom ), the type with no values.

3

Set

Types and values in Agda are treated similarly. As value can be of a certain type, the type itself can be of a type of something, this something is called Set. For example 0 : ℕ : Set means that zero has type of natural numbers (or just 0 is a natural number) and natural numbers are of type Set (or natural numbers represent type or set). But it doesn't end here, because even Set has type Set₁, which has type Set₂ and all the way up to infinity (and beyond).

4

data keyword is used to define types in Haskell's GADT (Generalized Algebraic Data Types) style. Here are some examples

Empty type

data ⊥ : Set where

Boolean type

data Bool : Set where
  false : Bool
  true : Bool

Natural numbers

data ℕ : Set where
  zero : ℕ
  suc : ℕ → ℕ

5

f = f

Spaces around operators are mandatory, so we can only now construct some simple definition. This snippet is a valid definition of non-interrupting program in Haskell, but it won't compile in Agda due to the Termination check failure. Agda is a total language, meaning every program in it should terminate and there is no way to construct a valid non-terminating function. The reason behind it is that this function can be of an arbitrary type f : ∀ A → A, and due to Curry–Howard isomorphism between programs and proofs, constructing a value of any type basically means that we proved everything!

6

record

Agda has records, datatypes with single constructor. For example we can define a pair like so

record Π (A B : Set) : Set where
  constructor _,_
  field
    first  : A
    second : B

And we can define pairs now p = (zero , false) (parenthesis can be omitted) and extract fields from them: Π.first p is zero and Π.second p is false.

Also there is a convention to define a type with one element as an empty record

record ⊤ : Set where

There is only one value of type , which automatically deduced to be an empty record record {}, it can be used to define true propositions.

7

∃ n = n

For an arbitrary type of n this is just an identity function, but if it has type for example ∃ : ℕ → ℕ then it can be interpreted as a proof that natural numbers exist!

8

λ n -> n

The same identity function can be written as an anonymous function (lambda). It can be written as a 7 length snippet with instead of ->, but I can't come up with a more interesting 8-snippet otherwise.

9

λ x _ → x

This would be a definition of a constant function that returns its first argument and discards the second. A complete defintion with the most general type that works with argument types of any universe looks like this

const : ∀ {α β}
       → {A : Set α} {B : Set β}
       → (A → B → A)
const = λ x _ → x

Stuff inside curly brackets {} tells Agda that this variables are implicit and they should be decided based on the explicit variables A and B. It's possible to include them anyways like this const {α} {β} {A} {B} x _ = x.

10

Th = ⊥ → ⊤

Here I defined a theorem Th : false implies true. I can prove it by constructing a value of type Th. As I mentioned earlier a true proposition has only one value and it also represents an empty record and the proof would be just returning it

f→t : Th
f→t = λ _ → record {}

Similarly we can proof ⊤ → ⊤ or ∀ A → ⊤, so basically anything implies true propositions. Contrary to false propositions, which can't be proven without constructing a value of empty type. We can proof ⊥ → ⊥ by absurd pattern and ⊤ → ⊥ can't be proven. Therefore a complete implication table in Agda is represented in following statements

f→t : ⊥ → ⊤
f→t = λ _ → record {} -- empty record

t→t : ⊤ → ⊤
t→t = f→t -- same proof

f→f : ⊥ → ⊥
f→f () -- absurd pattern

t→f : ⊤ → ⊥
t→f = {!!} -- nothing could be written here, just a hole

11

¬ P = P → ⊥

The definition of propositional negation. You can look at it this way: if ¬ P is true then P is false and therefore should imply false (P also should be implied from false, but everything is implied from ). Given this definition it is possible to prove some theorems, like contradiction A → ¬ A → B, contraposition (A → B) → (¬ B → ¬ A), double negation A → ¬ (¬ A) and ¬ (¬ (¬ A)) → ¬ A. Note that Agda being an intuitionistic system, the double negation elimination ¬ (¬ A) → A is not a theorem: "It's not the case that it's not raining" doesn't mean "it's raining", but only that the rain would not be contradictory.

12

Usually in is written as , but I'm short of one character

x in P = P x

Types of functions from type A to some Set _ can be thought of as a usual set in maths sense, set membership therefore has type _∈_ : ∀ {ℓ} → A → (A → Set ℓ) → Set _. Empty set is then simply ∅ = λ _ → ⊥ and the universe (the set that contains every element of type A) is U = λ _ → ⊤. Other related definitions include

x ∉ P = ¬ x ∈ P
∁ P = λ x → x ∉ P -- complement set of P
P ⊆ Q = ∀ {x} → x ∈ P → x ∈ Q -- subset

13

V A : ℕ → Set

This is a simplest data declaration for vectors (lists with size). The full definition with constructors looks something like this

data V A : ℕ → Set where
    []  : V A zero
    _∷_ : ∀ {n} → A → V A n → V A (succ n)

Notice that it's a dependent type, it depends on the value of type ! Now the function like head which returns the first element of a vector can be defined without worrying about empty vector case, we just give it a type that works only with non-empty vectors like so

head : ∀ {n} → V A (succ n) → A
head (a ∷ as) = a
\$\endgroup\$
2
  • \$\begingroup\$ Wow! Where do I get a compiler / interpreter? \$\endgroup\$
    – cat
    Commented Apr 28, 2016 at 2:38
  • \$\begingroup\$ @cat sure \$\endgroup\$
    – swish
    Commented May 8, 2016 at 0:05
27
\$\begingroup\$

Befunge-98

(No love for my favorite language?)

Befunge is a 2D programming language operating on a toroidal space - the 'grid'. In addition to the normal operators (all of which are single ASCII characters), there are also special instructions that change the direction in which the instruction pointer moves through the grid. The language was designed to be as hard as possible to compile, to this end, it contains elements of self-modification.

There are two versions of Befunge: Befunge-93, the first version (which limits the grid size to 80x25 and, as such, is not Turing-complete); and Befunge-98, the final specification (which allows unlimited grid size and much other useful functionality). In this post, I will use Befunge-98 for the code snippets because I feel it is the more useful of the two; a note will be included next to those snippets which are compatible with Befunge-93.

I recommend using CCBI to run longer code in Befunge-98. There are some other options for if you want to see Funge-space and the stack while the program is running: this online Befunge-93 interpreter (with 'klunky' input), and this online Befunge-98 interpreter (with no input at all, though it runs fast).

Snippets

Length 1 (Also works in Befunge-93)

.

Prints out 0, forever and ever and ever. Because Befunge's space is toroidal, the pointer wraps around when it encounters an edge. Befunge starts with an empty stack for its memory; trying to pop or do operations on an empty stack makes it 'generate' as many zeroes as needed for the operation.

Length 3 (Also works in Befunge-93)

&.@

(Still kind of a boring example, but less so.) This one accepts a decimal number (&) from stdin and prints it (.) to stdout. Then - aha, a new feature! - it terminates at the @. This is a pretty boring program, but you can only do so much with three characters...

Length 4 (Also works in Befunge-93)

1+:.

Another infinitely looping program. Each loop takes the top number on the stack and increments it, duplicates it (with :), and prints one of the duplicates, leaving the other on the stack for the next loop. (Since printing a number removes it from the stack, duplication is needed in order to keep a copy.) The result of this is a program that prints the positive integers, starting from 1.

Length 6 (Also works in Befunge-93)

8:*00p

Unless the user can watch Funge-space while the program is executing, this program appears to do nothing. In fact, it even terminates, rather than looping infinitely. "How?" you might ask. "You said before that the @ operator ends the program, and there is no such thing here!" Here lies one of the most intriguing aspects of Befunge: the ability for the program to modify its own instruction space.

The p operator takes a number, let's call it n, and a coordinate pair x, y (in order such that y is on top of the stack), and puts the character with codepoint n in the Funge-space grid square at the given coordinates. In this case, it puts an @ (ASCII value 64, or 8*8, or 8:*) at position 0, 0 - the top-left corner of the program, where the 8 is initially. Then, wrapping around, the pointer hits the @ it just set down and stops - the program has modified its own code. There is also a g operator that grabs the value of the character at the given coordinates; in this way, the program space can also be used as program memory that's more convenient than the stack.

Here's where Befunge starts to show its true colors! It's a cunning and devious language.

Length 7

~:a`j@,

Here we start seeing interesting constructions, and also some features that are not in Befunge-93. This program takes exactly one line of text and prints it out again - specifically, it keeps accepting characters from stdin (using ~) and checking whether the character is greater than 10 (a, new to -98), the value of a newline. If it is, it prints; if not, it terminates. This is accomplished using j (also new to -98), our first control operator - which pops a value and jumps over that many instructions - in this case either 1 (if the character value is greater than 10) or 0 (if it is not).

Length 8

1#;::.+;

This introduces the # operator, or trampoline, which jumps the instruction pointer over the next symbol to execute - the same as 1j. It originated in Befunge-93, due to the necessity of such an operator in a two-dimentional language. We can also see ;, a 98-exclusive operator that also moves the pointer around - this one jumps it all the way to the next ; along the direction the pointer is moving. Here it's used to create an infinite loop so the initial 1 only pushes a 1 at the beginning. The end result is a program that prints out, starting at 1, sequential powers of 2 forever and ever.

\$\endgroup\$
3
  • \$\begingroup\$ I feel your pain. I think this contest is over and my awk entry was just made too late. \$\endgroup\$
    – kojiro
    Commented Jan 28, 2015 at 15:12
  • 3
    \$\begingroup\$ I feel your pain too and upvoted you, if you're feeling kind you might watch my Rebmu video in return :-) \$\endgroup\$ Commented Jan 28, 2015 at 16:46
  • \$\begingroup\$ @Kasran You have 21 up-votes now. You could publish some pretty interesting things. Some ideas: random number generator, maze generator, maybe even a maze solver. \$\endgroup\$ Commented Oct 31, 2015 at 5:32
27
\$\begingroup\$

Jelly

Factoid

Jelly is inspired by J and, in particular, its trains. Everything in Jelly – including literals – is a link (function), and you can combine several links by simply chaining them together.

As a tacit language, Jelly programs usually do not require variable references. Also – like J – many of Jelly's atoms (built-in functions) vectorize automatically. This makes Jelly fairly competitive in code golf competitions.

Length 1

b

This full program is a neat little base conversion utility. It takes an integer n as left and a base k as right argument (resp., first and second command-line argument) and converts n to base k.

Now, since integer-to-base conversion only makes sense if both arguments are numbers, the atom b vectorizes with depth 0, meaning that it "searches" for corresponding numbers in b and k.

For example, [n1,n2] b [k1,k2] converts n1 to base k1 and n2 to base k2, while [n3,n4] b k0 converts both n3 and n4 to base k0. Moreover, the list don't have to be rectangular. Combining the two previous examples, [[n1,n2],[n3,n4]] b [[k1,k2],k0] gives the same results as before.

Try it online!

Length 2

»\

Aside from atoms, Jelly has quicks. While a few of them are similar to atoms and simply execute some code, the vast majority affect the behavior of one or more atoms to their left.

For example » on its own is a dyadic atom that returns the maximum of two numbers. The quick \ pops the link » from the current chain and pushes the quicklink »\ in return, which performs a cumulative reduce by maximum, i.e., it computes the cumulative maxima of a list of numbers or characters.

For example, [n1,n2,n3,n4] »\ computes max(n1), max(n1, n2), max(n1, n2, n3) and finally max(n1, n2, n3, n4), and returns the list of all four results.

Try it online!

Length 3

+×_

Any chain of links is parsed in a particular fashion, which depends both on the arities of the involved links (i.e., the number of arguments they expect) and the arity of the chain (i.e., the number of arguments passed to the chain).

If the above full program is executed with two arguments a and b, sum, multiplication and difference are all dyads, +×_ becomes a dyadic fork; the outmost links are evaluated first, then the inner link is called on both results. In this particular example, the result is (a + b) × (a - b) = a² - b².

Try it online!

If the program is executed with a single argument c, each of the links in +×_ is a monadic hook, meaning that is gets called with te previous return value – initially the input argument – and the input argument. Our example thus computes ((c + c) × c) - c = 2c² - c.

Try it online!

Length 4

’!²%

This full program – intended to be run with a positive integer (or a list of positive integers) as sole argument – is a primality test based on Wilson's theorem, which states that an integer n > 2 is prime if and only if (n - 1)! ≡ -1 (mod n).

Since (-1)² = 1 and (n - 1)! is divisible by n is 1 or composite, ((n - 1)!)² % n is 1 if n is prime and 0 otherwise.

The code consists of three monadic atoms (decrement, factorial, square), which are parsed as atops (i.e., they are applied one after the other, each on top of the previous one), and the dyadic modulus – a hook – which gets called with the previous return value and the original n as left and right arguments.

Try it online!

Length 5

“wat»

Jelly has built-in string compression. While it has a few limitations – only produces printable ASCII and only compresses dictionary words – it performs rather well under these conditions.

The characters between and » are replaced with their indices in Jelly's code page, which are then interpreted as the as digits of a bijective base-250 number. In turn, this number arithmetically encodes either an index in the dictionary of short or long words, or a single printable ASCII character.

All arbitrary sequences of Jelly's code page's characters decode to something; the example string wat is decodes to the following.

 stickup Aachen

Try it online!

To compress strings, you can use this script by @Lynn.

\$\endgroup\$
1
  • 14
    \$\begingroup\$ Where are the more snippets? \$\endgroup\$ Commented May 7, 2016 at 14:57
27
\$\begingroup\$

Lua

Factoid

Lua is a dynamic, lightweight yet powerful, highly portable (pure Ansi C), fast and easy to learn scripting language.
Initially designed to be a configuration language and to be embedded in applications to script them, it is also used as a glue between native libraries and to be a standalone language on its own.

Length 1

;

You will nearly never see a semi-colon at the end of a Lua statement (unless that's the taste of the coder!), as they are totally optional and, most of the time, unnecessary. They can be used if you want to put two statements on the same line (even then it is optional: a = 5 b = 3 is OK (but ugly!)) and to avoid some ambiguity: a = f (f1 or f2)(x) can be seen as a = f; (f1 or f2)(x) or as a = f(f1 or f2)(x) (call of f with a function argument returns a function which is called with x as argument).
The semi-colon can be used as separator in table literals, too.

Length 2

..

That's the string concatenation operator in Lua. If we concatenate a number, it is converted to string. For something else than strings or numbers, the __concat metamethod is called (more on this later).

Length 3

nil

is a special value, whose main property is to be different from any other value... It is generally used to represent the absence of a useful value, equivalent to null in some other languages.
It is the only other value that is "falsy" (the first one being false, of course), any other value is coerced to true in a conditional expression.

Length 4

f's'

The function f is called with the literal string "s". Note that literal strings can use single quotes or double quotes as delimiters.
Here, as a function called with a single, string argument, we can omit the parentheses. That's syntax sugar for f('s'). This can be used for writing some nice DSL.
This syntax shortcut can be used too when the single argument of the function is a table.

Length 5

a={1}

The variable a is assigned with a table with one entry, 1.
Here, the table is treated as an array. We will see they can be also associative arrays (key / value).
Table is a fundamental data structure in Lua, so it is optimized and efficient: it can have both an array part (with fast numerical index access) and a hash part for the associative side.

Length 6

[[\n]]

A literal string (long format) made of two characters: backslash and n. The [[ ]] notation allows to write multi-line strings with no escapes inside. Newlines are kept literally (except the one immediately after the opening bracket, if any: it is ignored for convenience of formatting).
Lua allows nesting of long literal strings (eg. if you want to put one inside another) by putting a number of = sign between the two brackets. Of course, matching closing brackets must have the same number of equal signs.

Length 7

t={k=v}

A table defined as associative array: here, k is a shortcut for ['k'], a string key (the latter annotation is useful for string keys that are not valid identifiers). v is a variable, its value will be the value of the entry.
The key (index) can be any Lua value, except nil. The value can be any Lua value, but nil actually removes the entry.
Access to entries can be done as t.k or as t['k']. The first form is valid only if the key is a valid identifier, otherwise we have to use the second form.

Length 8

a,b=f(x)

A function can return several values (put them after the return keyword, separated by commas), and these values can be assigned at once to several variables.
If the function provides more values than the number of left-hand variables, the extra values are dropped.
If it doesn't provide enough values, the extra variables get nil as value.
A common pattern in Lua is to return either a single value, or nil and an error message if something went wrong.

Length 9

--[[ C ]]

A block comment. Line comments are marked with a double dash. Block comments extends this notation with a block of text (potentially multiline) marked between double brackets. Actually, they use a syntax similar to long literal strings, including the equal signs between the brackets, whose number allows to distinguish nested blocks. This allows to avoid conflicts with other block comments or long literal strings when commenting out a long block of code.

Length 10

local v={}

Lua started its career as a configuration language, and is still useful as such. Because of this, its variables are global by default, ie. they are attached to the built-in _ENV variable and visible everywhere. That's also where we find the standard libraries, for example.
Of course, this global environment is to be avoided for most usages, because of collision risks, encapsulation issues, and because a global variable is slower than a local one.
Lua supports lexical scoping, we can define variables that are visible only within their scope, their chunk (from the declaration point to the end of the chunk) and the nested chunks.
The statement above declares a local variable initialized to an empty table.
For performance reason, a common practice is to bring global functions to the local scope, like local print, find = print, string.find.

Length 11

a,b,c=b,c,a

As seen, a function can return several values, which can be assigned in one go to several variables.
It also works with several values (separated by commas) on the right hand side.
The expression above cyclically permutes the values of a, b and c, ie. a takes the value of b which takes the value of c which is assigned the value of a. It is a variant of the a, b = b, a expression which swaps two values.

Length 12

::L:: goto L

The programming world frown upon the usage of GoTo, but the Lua authors consider it is malevolent only in bad hands... They introduced it in Lua 5.2 to answer a frequently asked feature: adding a continue statement. The goto statement effectively allows to jump to the end of a loop, and also allows to break out of several nested loops. Note that Java, which has goto in its reserved words, doesn't implement it, but have named break allowing such feature...
Here, goto SomeName jumps to a scoped label named... SomeName, which is defined by surrounding the name with double colons like ::SomeName::

Length 13

(a or b){x=1}

This is a function call with a table as argument. Lua allows the syntax sugar of omitting the parentheses around the argument if it is unique and it is a table, similar to the call with a string seen at length 4. It allows to create some nice DSLs...
Here, we also see a logical expression between two functions: if a is defined, it is called with the argument. If it is not defined, ie. has the value nil, then that's b which is called (assuming it cannot be nil). This fallback syntax is idiomatic in Lua to provide default values to variables. It has the same function than the ternary operator of C-like languages (a ? a : b)
Note that in Lua, logical operators are spelled out: or and not instead of C's || && !, slightly less readable for newbies.

Length 14

_ENV={p=print}

Starting from Lua 5.2, local environment of a current function is exposed using variable _ENV. While its default value is _G, global environment, as any other variable, it can be assigned any value!
Here, we change local environment, one from which free names are resolved, to table including single key-value pair with string key p and value being built-in function print. After this assignment, p will be the only resolvable name in current environment.

Length 15

ffi.load'mylib'

While Lua have official implementation in ANSI C, others exist as well. One of most well-known ones is LuaJIT, in which this line would load C library called mylib.so on UNIX or mylib.dll on Windows and expose its functions directly to your Lua code. In addition to this, LuaJIT implements JIT-compilation for Lua code, greatly increasing its speed compared to official interpreter.
However, LuaJIT's last release was back in 2017 and it also implements Lua 5.1 API, making its usage now somewhat questionable. Newer JIT compiler for Lua is Ravi, that's based on LLVM and targets Lua 5.3 API. It also implements some language extensions.

Length 16

function N(a)end

You can create global functions with the function keyword followed by a name.

Length 17

N=function(a) end

The above snippet is syntactic sugar for this. local function N()end is sugar for local N=function()end. This is allowed because functions are first-class values.

Length 18

("n=%d"):format(3)

Wow, lots to introduce. This formats the string n=%d, replacing the %d with the number 3. The : denotes a method call, which is the same as calling ("n=%d").format("n=%d", 3). But wait, "n=%d" doesn't have the property format! Instead, since it isn't a table and doesn't have this property, Lua looks at its metatable, the global string table, and finds the format property there. Metatables are kind of like prototypes in Javascript. It then calls the string.format function with "n=%d" and 3 as its arguments, and returns "n=3".

\$\endgroup\$
3
  • \$\begingroup\$ As @Benjamin seems too busy to have time to update his entry, I take the liberty to start a new Lua entry, since it is allowed by the rules... I have some snippets ready, so vote up! ;-) \$\endgroup\$
    – PhiLho
    Commented Jan 29, 2015 at 9:58
  • 1
    \$\begingroup\$ Wonderful, I didn't even know you could use [[ ]] for multiline strings in Lua. Lua is rather under-appreciated. \$\endgroup\$
    – user23597
    Commented Dec 22, 2015 at 10:25
  • 2
    \$\begingroup\$ I love your answers and the information you added to each snippet. Please update, i want to see the other snippets :) \$\endgroup\$
    – pschulz
    Commented Jul 25, 2016 at 14:36
26
\$\begingroup\$

μ-recursive functions

These come in many flavors, but are all essentially the same: a "functional assembly" of sorts.

Factoid: μ-recursive functions are a Turing-complete model of computation that, unlike Lambda calculus (which is theoretically equivalent to it) has no more-or-less popular language based on it. Why? Because it manages to combine the readability of (((((Lisp)))))) with the eloquence of assembly. However, there are interpreters for several langauges that are actually flavors of μ. None of them, however, can operate with anything but unsigned integers. Pity.

μ, by default, supports only 2 datatypes - an unsigned integer and a function. Operators recieve and return functions, functions recieve and return unsigned integers. Simple and straightforward. That's all there is to the entire language.

If this recieves enough upvotes, I'll be providing snippets in RF, a small language based on μ-recursive functions created for educational purposes by a teacher at a university where some friends of mine study. It uses a flavor of μ that is a bit different from Kleene's. You can download it here: http://www.mediafire.com/download/fnsyze4crthgl89/rf_setup.rar (warning: entire interface is in Russian; function definitions go into the top text field, function calls go into the bottom left one, results get output to the bottom right one).

Length 1 snippet:

N

This is not runnable code, sadly. I'd need at least 5 upvotes for the first runnable RF snippet.

This is one of the 3 built-in functions supported by μ, the successor function. What does it do? Well, it simply takes one number as an input and returns this number + 1. It's also sometimes abbreviated as s in different μ languages.

Length 3 snippet:

f()

This is the shortest possible "input" call of a μ-recursive function. It calls a 0-ary (parameterless) function f with, well, no parameters.

As μ is a 100% pure functional language, input is restricted to function calls, and output is restricted to function return values. All μ-based languages, including RF, provide a way to list the function calls that the program should recieve as "input". Note that this specific example won't run in RF because it requires function calls to have a ; at the end, but it could run in another μ-based language.

Length 4 snippet:

M(O)

This is one of μ's 3 operators: the minimisation operator, sometimes abbreviated as μ. Obviously, it gives the model of computation its name. This specific snippet synthesizes and returns a 0-ary function that always returns 0.

Now, this calls for a little bit of theory.

What does this operator do? Its workings can be written concisely as follows:

M(f(a1, a2, ... an-1, an)) called with arguments (a1, a2, ... an-1) returns the least value of an satisfying the condition f(a1, a2, ... an-1, an) == 0

It takes an n-ary function f as input, and synthesizes and returns an n-1-ary function (i.e. taking one argument less than the input function).

What does the returned function do? When called with some arguments (a1, a2, ... an-1), it forwards them to the input function f. It then finds the least possible (i.e. starting from 0) value of the last argument (an) which, together with the forwarded arguments, will make f return 0. If f doesn't ever return 0 in these conditions - hello, endless loop. If it does, the synthesized function returns the value of an it found.

In the snippet above, the operator takes the 1-ary built-in function O, and synthesizes a 1 - 1 = 0-ary function which finds and returns the least value of the last (and, in this case, the first) argument that would make O return 0. As O happens to always return 0, the least value of the argument would be 0. That is what the synthesized function will return.

Interesting note: there are two main different notation for this, as well as the other operators. Kleene, for example, uses a notation that is the inverse of the one RF uses: in his texts, an is actually the first argument of the input function f, not the last one. However, this doesn't really matter.

Length 5 snippet:

O(1);

I promised a runnable RF snippet, now, here you go. This is a RF function call "input". It calls the built-in 1-ary function O mentioned in the previous snippet, which always returns 0, no matter what you pass to it. It can be really, really useful at times.

Length 6 snippet:

I[1,2]

This is the identity function, one of the 3 built-in functions. It can take several arguments and return one of them. It is defined as I[i,n](a1, a2, ... an) = ai

You can think of it as a function "template" of sorts. The square brackets can take 2 constant (nonzero unsigned integer) parameters, which determine the identity function's behaviour. The second parameter in the brackets is the number of the function's actual parameters. The first one is the index, starting from one, of the parameter that the function returns. For example, the function shown above can be read as follows: "define a function which takes 2 parameters and returns the 1st one".

Length 7 snippet:

S(N,O);

We finally reached another operator! S is the superposition operator. The piece of code above uses it to create an 1-ary function that always returns 1.

This operator can be expressed as follows: S(f0, f1,f2, ... fn) called with arguments (a1, a2, ... am) = f0(f1(a1, a2, ... am), f2(a1, a2, ... am), ... fn(a1, a2, ... am))

At least 2 functions should be supplied to the operator. f0, the first function, should have an arity equal to the number of functions passed to the operator besides it (i.e. for f1,f2, ... fn, the arity of f0 should be n). It cannot be a 0-ary function. All other functions passed to the operator should have an equal arity (i.e. f1,f2, ... fn should all have the arity m). The synthesized function shall also have this arity (m).

The synthesized function first calls all but the first of the operator's argument functions with the arguments passed to it, and then calls the first of the operator's argument functions with the others' return values and returns its result.

In the snippet above, for example, when we pass an argument to the created function, it calls O with this argument, which returns 0. Then it calls N with this return value, which returns 0+1 = 1, so the synthesized function also returns 1.

Length 8 snippet:

zo=M(O);

This is a function definition! You can call it with zo();. It defines the zero-arity (parameterless) function returning 0 that I already discussed above.

Now we're getting to the fun part, recursion!

Length 15 snippet:

f=R(zo,I[2,2]);

Here zo is the previously defined (length 8 snippet) function.

R is the recursion operator. The above snippet defines a recursive function that takes one input parameter, decrements it until it reaches zero, then returns zero.

This operator can be expressed as follows: f = S(f0, f1) called with arguments (a1, a2, ...a{m-1}, am) = if am > 0: f1(a1, a2, ... a{m-1}, am - 1, f(a1, a2, ... a{m-1}, am - 1)); if am == 0: f0(a1, a2, ... a{m-1}).

This is basically good old tail recursion, plain and simple.

Let's see how the function above works for a parameter x: first, we have f(x). If x > 0, we return I[2,2](x - 1, f(x - 1)), which is the same as f(x - 1), and so on until we reach f(0), in which case we return zo(), i.e. 0.

The recursion operator is very important in μ-recursive functions, it's the backbone of most of the logic. However, some of its uses may seem a bit strange:

Length 16 snippet:

de=R(zo,I[1,2]);

This function takes one parameter x and returns x - 1 (decrements), if x > 0, and returns 0 if x == 0. Implementing it as a counterpart to N is instrumental in implementing subtraction (just as N is necessary in addition).

This use of the recursion operator may be considered strange because, well, there's actually no recursion going on here at all! Consider: if x > 0, de(x) = I[1,2](x-1, de(x-1)), equivalent to simply x-1, so the tail call de(x-1) doesn't even happen! And if x == 0, it simply returns zo(), or 0.

Length 18 snippet:

de3p=S(de,I[3,3]);

I see we didn't have an example for the superposition operator already, but here we go now. This defines a function de3p which, using the previously-defined de, takes 3 parameters and decrements the last one (calling it as de(I[3,3](x,y,z)) = de(z), where x, y and z are the 3 parameters).

Using this function, we can now define subtraction!

Length 19 snippet:

sub=R(I[1,1],de3p);

The sub function takes two parameters, x and y, and returns x - y. How it does that is quite obvious: if y > 0, sub(x,y) = de3p(x,y-1,sub(x,y-1)) = sub(x,y-1) - 1. And if y == 0, sub(x,y) = I[1,1](x) = x. So, basically, the function calls itself until y is 0, then takes x and backtracks for y steps, subtracting 1 from x on every step, resulting in x - y.

Length 20 snippet:

next3p=S(N,I[3,3]);

I decided to show a runnable example with every built-in function and operator; this is the last one, the built-in function N. This defines a function next3p, which takes 3 parameters and increments the last one by 1: next3p(x,y,z) = z + 1. This is pretty much by analogy with the previous example and doesn't really need an explanation.

Now, using this example, we can do addition!

Length 21 snippet:

ad=R(I[1,1],next3p);

This defines a function ad which takes 2 parameters and adds them together. It works the exact same way as the subtraction function, the only difference being that 1 is added to x on every backtracking step.

\$\endgroup\$
9
  • \$\begingroup\$ can you show how would it be possible to subtract one from an input, or check for equality? \$\endgroup\$ Commented Apr 9, 2016 at 1:24
  • \$\begingroup\$ lots of upvotes! please update? \$\endgroup\$ Commented May 3, 2016 at 4:21
  • 1
    \$\begingroup\$ @proudhaskeller: I added examples for recursion, decrementing, subtracting and adding. Checking for equality is more verbose, but a simple way to check if x==y is to subtract x from y, then y from x, then sum the results: if the final result is 0, the two numbers are equal, if it's not, they're not equal (using the defs in the answer, it'll be something like eq=S(ad,S(sub,I[1,2],I[2,2]),S(sub,I[2,2],I[1,2]));). \$\endgroup\$
    – Mints97
    Commented May 11, 2016 at 15:03
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ: I updated the answer with some new examples. \$\endgroup\$
    – Mints97
    Commented May 11, 2016 at 15:04
  • 2
    \$\begingroup\$ Fascinating. This is some beautiful stuff \$\endgroup\$ Commented May 11, 2016 at 16:50
26
\$\begingroup\$

dc

Almost nine months later -- I can't believe dc is not on the list!

Factoid

dc (desktop calculator) is a Unix utility older than the C programming language, and also the hardest programming language to google. Luckily it's probably preinstalled on your Linux, Unix or Mac box, and available for Cygwin too!

Length 1

1

dc is a stack oriented language. 1 is an instruction that pushes the number 1 one the stack so that we can use it for other instructions.

Length 2

?f

These two characters is a whole dc program that actually does three things! It takes a line of input, evaluates the input as dc code, and prints the contents of the stack afterwards. You can feed it with the next snippet that I will post if I get another vote :)

Length 3

zzp

z pushes the current stack depth. Initially the stack is empty, so 0 is pushed on the stack. The stack is then 1 deep, so the next z pushes 1. p prints the top of the stack, which at this point is 1 (although the stack depth is now 2 :D).

Length 4

1A0F

dc supports number input to be in any base from 2 to 16, so the characters 0123456789ABCDEF all work as digits. Input numbers are not limited to only digits found in the current radix, but they still respect the positions of that base. This means that in base 10 (which is the default), the given snippet evaluates to 1*10^3 + A*10^2 + 0*10^1 + F*10^0 = 2015 :)

Length 5

O[P]x

A convoluted way of printing a newline! O pushes the current output radix (which defaults to 10 and is independent of the input radix). [] defines a macro and pushes it. x pops the macro and executes it. P pops and prints a value as a byte stream.

Length 6

[dx]dx

Duplicate and execute, duplicate and execute, rinse and repeat. One copy of the macro is always left on the stack, so this loops forever. On some systems or implementations it may crash.

Length 7

[]sf7>f

This is sort of an if-statement: It will execute the empty [macro], which is first stored in register f, if the top of the stack is less than 7. Intuitive, huh? Just wait for an if-else! I will need way more characters for that though ;)

Length 8

3812649P

Prints a smiling face :-) Another example of the P command. 3812649 is the character points of the smiley string shifted to their correct position in base 256 and added together. Very useful technique for creating quines and quine-like programs.

Length 9

[9<L]dsLx

This is kinda the standard template for a loop -- 9 can be replaced with any code, and you can use other comparisons than <. As the snippet stands now though, it is perhaps not the most useful thing in the world:

The comparison consumes one element in addition to the 9 that is pushed every time, so the snippet will pop each element down to, and including, the first element which is less than or equal to 9. If it were to empty the stack, the last comparison would fail with a warning, and leave the 9 on the stack.

Length 10

6581840dnP

If I had actually counted how few characters it takes beforehand, I guess I wouldn't have ruined the surprise just two snippets ago, but yeah... this is a quine.
(That means that the program prints out its own source code)

Length 11

I just came up with this for the dc golfing tips post, and I'm quite excited because I'm absolutely sure that this is the shortest possible way to write an if-else-statement!

Suppose you want to do if top-of-stack == (THAT) then (THEN) else (ELSE)

[[(THEN)2Q]sI(THAT)=I(ELSE)]x

Uses the I register. The placeholders (THAT), (THEN) and (ELSE) isn't part of the byte count, and = can of course be exchanged with any of >, !>, <, !<, !=.

\$\endgroup\$
26
\$\begingroup\$

Ruby

Created by Yukihiro "Matz" Matsumoto in 1995, Ruby is a dynamical object-oriented programming language. It's built/inspired by Perl, Smalltalk, Eiffel, Ada, and Lisp.

Matz, speaking on the Ruby-Talk mailing list, May 12th, 2000.

Ruby is simple in appearance, but is very complex inside, just like our human body

Factoid
In Ruby everything is objects, so no primitives. Parentheses are also optional. Opening up for some interesting coding, but that doesn't mean that you have to avoid them.
Is this really that readable?

puts array.delete hash.fetch :foo

Snippet 1
Use the $ to create global variables, but don't clutter the namespace please.

Snippet 2
To create a new hash, all you need to type is {}.

Snippet 3
Ruby uses nil as a false value. So no need to do var.nil? everywhere.

Snippet 4
puts is used to print a string version of an object with a new line at the end. Short for "put string". Can also be shortened to just p.

Snippet 5
To make Ruby even more powerful it handles closures. And with the use of f.call you can call/invoke a block or function. Pretty sweet. For those unfamiliar with closures. A closure can pass it around like an object (to be called later). It also remembers the values of all the variables that were in scope when the function was created. It can access those variables when it is called even though they may no longer be in scope.

Snippet 6
The snippet class C returns nil, and that is because everything in Ruby has a return value. You can even return multiple values.

Snippet 7
With the use of include Ruby support single inheritance. Making it easy to mixin modules.

Snippet 8
x||=true is one of several logical operators that Ruby supports. This one checks if x has been defined, and if not sets it to true.

Snippet 9
Fo.new(x) calls the class Fo initialize function, with the value of x. There is no constructor in Ruby so you are free to return what value you like from the .new() call.

Snippet 10
As mentioned earlier Ruby supports multiple return values, and it is easily done with return x,y. The values are returned as they are read, and if you have more return values then what you have for assigning the rest will be dropped. Using the * on the last variable will make an array and assign the rest of the return values to that array.

Snippet 11
RubyGems is the packet manager for Ruby started in November, 2003. Original a stand alone program, but as of Ruby 1.9 it is a part of the standard library. Use the code snippet gem install and the name of the package (for example 'sinatra') to install it.

Snippet 12
[1,2]<<[3,4] The command '<<' pushes or append a object to the array. In our case the array [3,4] will be pushed 'into' the array [1,2], making it 'look' like this [1,2,[3,4]]. So it does not merge two arrays.

Snippet 13
x.map{|y|y+1} The map function iterates over the array 'x' and invokes the block given, and returning a new array with the modified values. In our case it will iterate over the values in the array and increment them with one.

Snippet 14
x.map!{|y|y+1} This snippet is similar to the previous one, but calls on the function map!. The '!'/exclamation mark tells the user that this function will modify the object calling it, often called destructive or dangerous functions.

Snippet 15
The snippet ARGV[0] ||false checks if ARGV[0] evaluates to true, if not it will return the or value, false. ARGV is an array containing the arguments sent in at start time. ruby app.rb test will give you 'test' in ARGV[0].

PS: Also check out this post about Ruby

\$\endgroup\$
1
  • \$\begingroup\$ 1 more upvote. p should be there I think \$\endgroup\$
    – Anwar
    Commented Oct 24, 2016 at 8:51
26
\$\begingroup\$

Swift

Factoid

Swift is a compiled language created by Apple, introduced in 2014 and is meant to replace Objective-C, the first supported language for OSX and iOS. Swift is currently used for iOS, macOS, tvOS and watchOS development. It uses the LLVM Compiler

It focuses on writing less code (compared to Objective-C, which is very verbose) and handling safer types. It features type inference, first-class type functions, closures, optional types, enum associated values and many more.

Swift is REPL, you can make your own idea by trying it on http://swiftstub.com/, or http://www.runswiftlang.com (these sites were shut down), use https://swift.sandbox.bluemix.net/#/repl instead.
Sites keep being closed, use https://www.weheartswift.com/swift-sandbox/.

Snippets:

14

case let(8,x):

In a switch case, this statement is absolutely correct.
That switch must have a tuple with two values. When evaluating the expression, if the first value is 8, it enters the case and fills the x variable with the second value of the tuple so you can access it directly inside the case.

11

/** #YES */

In Swift 2.0, comments can be written in Markdown. This produces a big title with YES as text. It can be displayed with format in the help navigator or quick help in Xcode.

10

var i=10e8

It creates a double value with 1000000000.0 in it. You can even write it like this 1_000_000_000.0. Swift accepts different number notations for scientific or currency purposes. It all leads to the same value in memory, but helps to clarify source code.

9

f(#i:int)

When declaring a function, you have to name the formal and the actual parameter, but sometimes the actual parameter name is already a good formal parameter name. Instead of writing the name twice at declaration func myFunc(aMarvelousInt aMarvelousInt: int) you put a hash symbol in front of the parameter func myFunc(#aMarvelousInt: int).
This feature has been removed from Swift 2.0 because it's the default behavior. To prevent using the variable name as a method label, insert an underscore and a space before the variable name func myFunc(_ aMarvelousInt: int)

8

Array<T>

Swift have generics, you can only insert objects of the specified type. The short notation of that array is [T]. In case you want to insert different types in an array, you must specify the type AnyObject, or Any if you don't insert NSObjects inside.

7

let π=3

This declares a constant π containing a approximation of pi. In Swift, source code is in Unicode. Your variable names can even contain emojis 😃🚀🐑.

6

"\(i)"

This returns a String with the value of i in it. The backslash escape character followed by a value in parentheses evaluates the content and inserts it in the string, or if it's a printable object, it uses its description.

5

(3,7)

This is a tuple with two integers. Tuples can be used to make functions return several values. To get the values, you specify the index. (3,7).1 returns 7. You can also name the values at declaration and access them with an identifier. (hours: 12, minutes: 46, meridiem: "PM").minutes returns 46.

4

func

That's the way to declare functions. A function is a first class object.

3

let

That's the way you declare constants. Constants have an optimisation in the compilation phase compared to the var declarations. An example is let hoursInADay = 24.0. Type inference makes that constant a Double.

2

..

This was the operator for half opened range in Swift 1.0, but to avoid ambiguity with the closed range operator ..., it has been replaced with ..< in Swift 1.1

You can use them in for loops (for x in 0..<5), on in switch cases (case (0..<5): break)

1

;

All Semicolons are facultative, until you put more than one instruction in a line.

\$\endgroup\$
5
  • \$\begingroup\$ I didn't realize that Swift is a compiled language. Is it JIT compiled? \$\endgroup\$
    – Alex A.
    Commented Feb 24, 2015 at 19:23
  • \$\begingroup\$ I think it's not JIT compiled. \$\endgroup\$
    – Crazyrems
    Commented Feb 24, 2015 at 21:13
  • \$\begingroup\$ Huh. Looks like you're right. For some reason I thought it was either JIT compiled or interpreted. Whatever. +1 from me the other day, keep 'em coming! \$\endgroup\$
    – Alex A.
    Commented Feb 24, 2015 at 21:24
  • \$\begingroup\$ @AlexA. It really looks like an interpreted language! For a long time, whenever I saw Swift code I'd think "This code will be slow," even though Swift is very fast. \$\endgroup\$
    – NobodyNada
    Commented Jul 22, 2015 at 19:08
  • \$\begingroup\$ In fact, Swift has a JIT compiler so you can use it as a scripting language, but initially it's designed to have static typing. \$\endgroup\$
    – Crazyrems
    Commented Feb 5, 2019 at 9:50
26
\$\begingroup\$

Awk

Factoid

Awk is a pithy programming language oriented toward string manipulation that also happens to be part of the POSIX standard set of utilities. Awk is named after its original authors, Alfred Aho, Peter Weinberger, and Brian Kernighan. Awk is often used in a pipeline, but large programs have been written in it (pdf, 127KB), too.

0 Characters

Nothing in life is free: an empty awk program prints nothing and exits successfully. (And seems to be the only awk program that doesn't read standard input.)

1 Character

1

An awk program consists of patterns and actions. Omit the action and awk assumes { print }. The above pattern is always true, so awk behaves exactly like cat.

Divergence: Some versions of awk, such as Kernighan's One True Awk consider both the empty string input and the always-true pattern illegal. POSIX says

Either the pattern or the action (including the enclosing brace characters) can be omitted.

So it comes down to whether or not 1 can be considered a pattern.

I'll try to rationalize the divergence between different versions of awk as long as I get more upvotes.

2 Characters

$3

The above pattern is true if the third field has value. If it does, awk will print the whole line. Thus, as a whole awk program, the above will filter all lines that have fewer than three fields.

Once again, the One True Awk does not consider $3 a pattern.

3 Characters

int

BSD treats the above as int($0) and prints every line that can evaluate to a nonzero integer.

Most other awks I tried, including GNU awk consider this invalid. POSIX categorizes int as an arithmetic function and says what it does when invoked without parentheses is undefined.

4 Characters

NF<4

This pattern causes Awk to print those records that have fewer than four fields in them. All editions of awk I tested behave consistently.

5 Characters

/foo/

Boring though it may be, it's time to introduce actual regular expressions. This one will match any line containing the string "foo". This is Awk's bread and butter, and also why it's fairly unnecessary to combine awk and grep.

6 Characters

$NF=NR

This expression overloads the assignment operator = and assigns the number of the current record (row) to the last field. Treating assignments as booleans has the same caveats you might expect from another language. For example $NF=NF would set the last field value to the number of fields, but would skip empty rows.

7 Characters

!(NR%2)

Will print out every other row. It will print the odd ones. I could have written NR%2==0 in the same number of characters, which is more flexible because I could also write NR%2==1 to get the complementary set of rows. I just picked the most obscure syntax because code golf.

8 Characters

!s[$0]++

is one of my favorite Awk expressions. The first time it sees a line it prints it. It never prints the same series of characters again. It's the tersest stable, sort-free uniq I know.

9 Characters

{print$3}

Print the third column. This is one of those boring, but important, Awk "fundamentals" that hopefully opens the door for cooler things with more characters. It's also our first action. (Remember from 1 Character that Awk programs are made up of series of patterns and actions.) Everything heretofore has been just patterns.

13 Characters

FNR<3{print}

Prints the top 2 lines of each file argument. Obviously the print command is redundant, but there were already examples of shorter code. FNR is the line/record number of the current file; whereas NR represents the total number of lines/records processed from all files.

14 Characters

BEGIN{FS=","}

The BEGIN pattern is true before any files have been processed. FS is the field separator pattern used to divide a line/record into fields. This line assigns the field separator before the first file is processed. It is equivalent to executing a script with the command-line argument of -F, with the benefit of not being required to remember to add the argument when running the script.

15 Characters

END{print FNR}

Prints the number of lines/records in the last file read. The END pattern is true after all input has been read, similar to wc -l

\$\endgroup\$
10
  • 2
    \$\begingroup\$ An even shorter way to do {print$3} (9c) is $0=$3 (5c), which has the added benefit of not printing blank lines when there is no third column. It also won't print when that third column is numerically zero; to do that, convert it into a string via $0=$3"" (7c). \$\endgroup\$
    – Adam Katz
    Commented Aug 29, 2015 at 2:01
  • \$\begingroup\$ @AdamKatz Just assigning $0=$3 isn't enough to print it. You also need a nonzero label, e.g. {$0=$3}1 which is 8 characters, and there's already an 8 character answer. :( Oops... I see what you were getting at. You are using $0=$3 as the label. Nice. \$\endgroup\$ Commented Apr 11, 2017 at 13:56
  • 1
    \$\begingroup\$ @RobertBenson – Yup! echo "1\n2\n3 4 5\n6 7 0 9\n10" |awk '$0=$3""' will give you 5 and 0 (using mawk 1.3.3) \$\endgroup\$
    – Adam Katz
    Commented Apr 11, 2017 at 19:36
  • 1
    \$\begingroup\$ Feel free to edit my answer as long as it's in the spirit of the "question". (IOW this isn't a code golfing challenge.) Some longer awk would be interesting. \$\endgroup\$
    – kojiro
    Commented Apr 11, 2017 at 21:21
  • 1
    \$\begingroup\$ @cnamejj @Adam Katz : just do awk '$0=_$3' - this would guarantee print as long as $3 isn't an empty string. So 0 in $3 works fine this way - i simply did a string concat, and forced the value being assigned as string zero instead of numeric zero. Using a single underscore for string coercion saves 1 byte versus using awk '$0=$3""' \$\endgroup\$ Commented Nov 15 at 1:09
25
\$\begingroup\$

Groovy

Length 17 snippet

import bob as Bob

An import alias. No need for fully qualified names on name clash.

Length 16

@CompileStatic()

Another AST. Since it's a dynamic a language, Groovy may run slightly slower than Java. This isn't usually a problem, specially when working with databases and network, but bottlenecks may happen. Enter @CompileStatic. This AST walks the tree representation and makes every call a more pure bytecode call, giving Java-like performance to your Groovy code. Here only Extensions and AST metaprogramming work. You can add it to a class and have it fully statically compiled, and have a single method of this class being dynamic using @CompileStatic(SKIP).

Length 15 snippet

No ideas.

Length 14 snippet

{}.setDelegate

Every statement written inside a closure bears an interesting property: you can change the object which will respond to them. Also you can set the resolving order of responding objects. The topic is lengthy and i won't go over details, but this is possible:

c = {
    gimme "wot!"
}

c.delegate = new Expando(gimme: { it }) // this guy will answer the 'gimme' call
c.resolveStrategy = Closure.DELEGATE_FIRST

assert c() == "wot!"

Length 13 snippet

s ==~ /^echo/

This snippet shows the (unofficially named) dynamite operator and a variant on string declarations. Groovy has a lot of ways to declare strings; 'simple-quoted strings', "double-quoted-with-interpolation-string", """multi-line string""" and what not. But those two stand over the crowd when it comes to regex: /slashy string/ and $/dollar-slashy-string/$. No need to escape stuff, yey: /\d+/!

Length 12 snippet

@TypeChecked

This is an AST Transformation. It walks on the class/method where it is annotated and checks for typing errors. Groovy was born as a pure dynamic language, although you could add types to method params and return. Later on, a lot of people coming from a Java background felt the terseness of Groovy was great, but the dynamic typing was not so, thus @TypeChecked was born. It will still allow Groovy's neat syntax, extensions and other compile-time metaprogramming to occur, but it will report errors on stuff unknown at compile-time.

Length 11 snippet

10.0 * 12.0

Oh, a mere float multiplication, you say? O noes. A digit-dot-digit in Groovy defaults to a BigDecimal, for arbitrary precision calculation. A must for financial calculations. Since operators are only allowed in Java using primitives (and something in String), using a lot of BigDecimals in Java can get messy; this snippet can be written in Java as new BigDecimal("10").multiply(new BigDecimal("20")). For floats, add an f: 10.0f, a d for double, a g for BigInteger, and a lot more.

Length 10 snippet

.metaClass

Every object in Groovy has this little property which is responsible for keeping up the MOP (Meta Object Protocol), which allows Groovy's metaprogramming: we can add methods, properties and even mix entires classes one into another to add functionality. It really shines when you are working on pure dynamic Groovy, but it is not limited to.

Length 9 snippet

a?.b?.c.d

The safe navigation operator. It stop navigating on objects which might be null. This won't throw a NullPointerException if a or b are null, but c must not be null.

Length 8 snippet

"a".tr()

The a object is a java.lang.String, but tr is not a method on Java's String. So what is going on here? Groovy features an Extension Mechanism. When the runtime finds an extension declaration in the classpath, it is automagically added to classes to enhance them. Extensions are statically compilable.

Length 7 snippet

[:]+[:]

Although the term is on pretty gray area, Groovy is a strongly typed language; the runtime makes little or no conversions between types. This snippet is really calling a well-defined method, which you can override, if needed. It can be understood pretty much as new HashMap().plus(new HashMap())

Length 6 snippet

a b {}

This snippet is parsed differently from snippet 5; from right to left. A method a receives the result of a method b receiving a closure/lambda as a param. Curly brackets {} is a closure/lambda/function, in Groovy.

Length 5 snippet

u w m

We can omit a lot of punctuation, as long as we remember Groovy's parsing order. This snippet is understood as u(w).getM().

Length 4 snippet

a*.b

The spread dot allows calling a method, or getting a property, from any iterable. This snippet is collecting the property b from every object in the list a (assuming it is a list).

Length 3 snippet

<=>

The spaceship operator! Calling this is akin to calling the compareTo method. Also chainable with Elvis: price <=> other.price ?: name <=> other.name

Length 2 snippet

?:

The Elvis operator (tilt your head sideways to see it ;-) ). Every class has an asBoolean() method. Elvis calls it (in a deep mississipi voice) and, when true, returns the value, otherwise, the else part. Checking an empty list? Easy: list ?: [1, 2, 3]

Length 1 snippet

&

An and operator. Groovy supports operator overload, but in a slightly safer way: they are overloaded through their names and only a subset of them is available. You can overload the & operator by implementing a method called and(param) in your class.

Factoid

Groovy is an alternative JVM language. It features AST Transformations, i.e., it is possible to walk the tree representation of the code and make whatever changes you'd like to it.

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Needs more ?. since that is just the best thing ever. Well, perhaps after Elvis, which you've already got. \$\endgroup\$
    – KRyan
    Commented Jan 20, 2015 at 22:08
25
\$\begingroup\$

Julia

Factoid: The Julia language was created as a fresh approach to technical and high-performance computing. It's free and open source.

Note: Though not a requirement of the competition, every snippet here can be evaluated at the Julia REPL without issue.


Length 7:

@time 1

Julia has built-in tools for profiling code. Among them are @time and @allocated, which are actually macros. Here we're using the former.

From the documentation:

A macro to execute an expression, printing the time it took to execute and the total number of bytes its execution caused to be allocated, before returning the value of the expression.

From the source code (at the time of writing):

macro time(ex)
    quote
        local b0 = gc_bytes()
        local t0 = time_ns()
        local g0 = gc_time_ns()
        local n0 = gc_num_pause()
        local nfs0 = gc_num_full_sweep()
        local val = $(esc(ex))
        local nfs1 = gc_num_full_sweep()
        local n1 = gc_num_pause()
        local g1 = gc_time_ns()
        local t1 = time_ns()
        local b1 = gc_bytes()
        time_print(t1-t0, b1-b0, g1-g0, n1-n0, nfs1-nfs0)
        val
    end
end

So what happens when we time the integer 1 at a freshly opened REPL?

julia> @time 1
elapsed time: 0.000521626 seconds (13880 bytes allocated)
1

13880 bytes allocated to print the number 1?! That seems a little excessive. But as it turns out, most of the allocation is due to the fact that Julia is JIT compiled. (Thanks to Martin Büttner for correcting me on the reason!) But if we were to run this again in the same session, we'd get something a little different:

julia> @time 1
elapsed time: 3.04e-6 seconds (80 bytes allocated)
1

That's much better!


Length 6:

≠(1,0)

What is that blasphemous character?! Those of us used to programming in the realm of ASCII may be initially put off by the presence of non-ASCII characters in source code. But fear not! Julia has your back. You can use a finite set of Unicode characters for input.

The operator is equivalent to !=, i.e. "not equal to". You can write it like ≠(1, 0) as in the snippet, or like 1 ≠ 0. Since 1 is obviously not 0, this returns true.


Length 5:

read!

No, Julia isn't commanding you to get up from your computer and read a book. In fact, read! is a function. In Julia, functions which modify their arguments end in !. In this case, read!(s, a) reads binary data from an input stream s and writes it to an array a.


Length 4:

1//0

Have you ever thought to yourself, "Man, I wish I could store an exact ratio of integers rather than a decimal value"? If so, you're in luck: Julia has a rational number type!

"But wait," you say, "I thought only Chuck Norris could divide by 0." Actually, Julia can deal with infinite rationals such as this one. However, it can't do 0//0... Only Chuck Norris can do that.


Length 3:

3\4

Julia has a built-in function akin to Matlab's backslash (\) operator that performs matrix division using a polyalgorithm. So A\b solves the matrix equation Ax=b for x. When you give it integers, like in this example, it's solving the trivial equation 3x=4, so the result is 4/3 = 1.333333.


Length 2:

im

This is a global constant which represents the "imaginary" number i, which is the principal square root of -1. Julia has a predefined type for complex numbers which supports all standard mathematical operations!


Length 1:

:

This returns colon(). The colon is used to construct ranges, like start:stop (assuming a step size of 1) or start:step:stop. Indeed, : actually calls the colon() function, so 1:4 is equivalent to colon(1, 4).

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

Rebol

All the examples below work verbatim in Rebol 3. Just type them into the Rebol 3 console (REPL) and see an immediate result. Obviously for example 14, if file.txt isn't present then it will throw an immediate error :)

25

find "foobar & baz" "bar"

This returns - "bar & baz"

find works on a series returning either a series where it matches or none if no match was found.

Some other examples:

find "foobar & baz" "boo"              ; none
find ["foobar" "bar" "baz"] "bar"      ; ["bar" "baz"]

24

random/only words-of lib

This returns a random word from the Rebol lexicon :)

lib is an object containing all the words defined by Rebol and also any created when importing modules. words-of returns a list of all the words within an object. random/only then picks one word at random from this list.

23

f: function [n] [n * 2]

This creates a new function called f which takes one argument and doubles the value received (the last expression evaluated is automatically returned by the function).

There are a few different function generators in Rebol to choose from. For eg:

  • function - all variables created within block are local

  • func - all local variables must be declared with /local refinement

  • does - has no arguments or local variables.

See Functions chapter from the Rebol/Core User Guide for more info.

22

reduce [1 + 2 * 3 red]

The reduce function evaluates multiple expressions and returns a block of results. There are two expressions in the above block so it returns a block with two values: [9 255.0.0]

NB. For the eagled eyed who were expecting 7 from 1 + 2 * 3 this is because Rebol has no operator precedence and simply evaluates operators from left to right. Use parenthesis to enforce precedence, for eg. 1 + (2 * 3) would return 7.

21

compose [blue (blue)]

This returns a block with [blue 0.0.255]

The compose function evaluates any code found in parenthesis (paren! datatype) but leaves everything else untouched.

20

red + blue = magenta

This returns true because Rebol supports tuple arithmetic.

19

type? [email protected]

Use type? to find the value's datatype. This example returns email!

NB. As you can see from the examples so far, Rebol comes with a lot of handy datatypes

18

$0.1 + $0.2 = $0.3

The above returns true because these are money! datatypes. So ideal for high precision arithmetic original link down at moment .

17

<div class="red">

This is a tag! datatype.

16

24:00 - now/time

This returns how long there is left in the day (in HH:MM:SS - a time! datatype).

NB. This code shows the first example of a refinement! in Rebol. With refinements you can modify the functions behaviour including adding extra arguments. By itself now would return the current date and time (date!). The /time refinement causes now to return the time only (time!).

15

{"a" {foo} "c"}

This is one way to represent a string! datatype in Rebol. Another way to express this would look like this "^"a^" {foo} ^"c^"" which isn't as visually appealing!

NB. Using braces over double quotes allows spanning of multiple lines and also nested {}. The ^ is used to escape the quoting delimiter. So {closing brace is ^} opening brace is ^{} would be how an unbalanced {} would look.

14

read %file.txt

This will read in the entire contents of file.txt into memory. Any word prefixed with % is a platform-independent file! datatype.

NB. read can also suck content down from other sources, eg. read http://www.rebol.com (this is a url! datatype).

13

100'000'000.0

This is the same as 100000000.0. Single quotes (') are allowed to split up numbers for readability.

NB. Commas can also be used to mark decimal places, eg. 100'000'000,0 is a valid decimal! datatype.

12

something: 1

This sets the word something to represent the value 1.

NB. Rebol is quite liberal in what can be used for a word as long as it doesn't clash with any known datatype. For e.g. another valid 12 length answer would be a-.+!&'*?: 1

11

12-Dec-2012

This is a date! datatype.

10

to-hex red

Functions in Rebol have fixed arity. The to-hex function expects one argument and returns a hex issue! datatype.

NB. The example given returns #FF0000 which is ideal for CSS colours.

9

#{FF0000}

This is hex (base-16) literal notation. Other bases for this binary! datatype are also available.

8

12:15:33

This is a time! datatype (HH:MM:SS).

7

newline

Gives Rebol's internal (platform-independent) newline character. Written as a character literal, this would be #"^/" -- the line-feed character.

NB. The # prefix here denotes a single character and not a string (ie. a series of characters like "foobar"). And the ^/ is Rebol way of representing the control code for LF.

6

speed?

Returns simplistic (and approximate) speed benchmarks for evaluation, CPU, memory & file IO. Handy for comparing the speed of your Rebol on different machines.

NB. General convention is that postfixing word with ? is used to signify what's / what is its. For eg. length? list or type? word

5

1 = 1

Equality test.

The operator = is infix synonym for equal?. == for strict-equal?.

NB. Spaces are important because 1=1 would be recognised as a word (and an invalid word at that).

4

why?

Explains the last error (that occurred) in more detail. It does this by opening your web-browser on the necessary webpage that documents the error.

For eg. foobar would produce the error ** Script error: foobar has no value. Typing why? next will open browser window pointing at http://www.rebol.com/r3/docs/errors/script-no-value.html

NB. This is the first function call example given. why? is a word which points to a defined function (source why? for details). When Rebol interpreter hits a word like this it invokes the function. If the function requires any arguments then Rebol evaluates the necessary words that follow and passes them to the function.

3

red

This returns a tuple which in this case is a tuple of RGB values (for the colour red!).

NB. And red is not the only colour defined in Rebol - http://rebol2.blogspot.co.uk/2012/03/color-names.html

BTW. Red also happens to be the name for an alternative version of Rebol - http://www.red-lang.org/

2

no

Rebol comes with a few synonyms for true and false... yes no on off

NB. These are all just words in the Rebol lexicon (including true & false) so all can be redefined. So if you peek underneath you'll find the truth is actually #[true] (literally!).

1

;

Everything after a semicolon to end of the line is ignored by the Rebol interpreter.

NB. Space(s) are important to Rebol because it interprets the words it sees. But ; is one of those exceptions where it cuts across this.


Factoid

Rebol is a dynamic programming language designed by Carl Sassenrath with data exchange in mind. NB. Douglas Crockford has cited Rebol for being an influence on JSON design.

It had been proprietary but Rebol 3 was finally opensourced on 12-12-2012 just before the world ended :) (according to the Mayan calendar!)

\$\endgroup\$
2
  • \$\begingroup\$ I'm sad this language isn't indev :c \$\endgroup\$
    – cat
    Commented Mar 17, 2016 at 21:05
  • 1
    \$\begingroup\$ @tac - Good news... it is "indev" :) See Ren/C which is a community fork of Rebol. In time this (or bits of it) will be fed back into mainline Rebol - github.com/metaeducation/ren-c \$\endgroup\$
    – draegtun
    Commented Mar 19, 2016 at 10:04
25
\$\begingroup\$

Smalltalk

Smalltalk has five keywords. The entire spec fits on a single sheet of paper.

Smalltalk is a small language ;-), with only a minimum number of builtin semantic features - basically the language only defines the syntax for how messages are sent to objects (that's what others would name "virtual function calling").

However, it comes with a big class library. This is open for inspection and extension, and includes everything from numeric operations to UI frameworks to compilers, editors, debuggers and class browsers.

Smalltalk is pure object oriented, with no exceptions. Everything down to integers, characters, stack frames, methods and closures is represented as an instance of a class. This includes classes themself, which are instances of a metaclass.

Every class can be extended, modified, subclassed or reinherited at execution time.

Every Smalltalk dialect comes with a powerful IDE, which makes heavy use of the above dynamic possibilities. For example, it is possible to change code in the debugger and proceed execution without any limitation. Programs are developed inside the IDE - that means that your application classes and objects live in the same world. There is no required separation between the IDE objects and the application objects, and each can make use of the other. of course, you can also extent the IDE itself, while you are living in it.

For programmers, the combination of powerful IDE and high dynamics due to the very late binding, make this a great environment for rapid development.

Length 1

Numbers evaluate to themselves - numbers are objects:

1

Length 2

Character literals (constants) are preceeded by dollar signs:

$1

Length 3

Strings are in single quotes, like in SQL:

'1'

Length 4

Literal arrays are stored in hash & parenthesis. These are created when a method is compiled, not at runtime, so it can improve performance:

#(1)

Length 5

Mixed mode arithmetic is done transparently. Values are coerced automatically as required:

1+2.0

Length 6

Blocks are anonymous functions. They can access the variables in their static scope. Blocks can outlive the dynamic scope in which they were created (i.e. they are Closures). Here is a simple block which returns its argument:

[:a|a]

Length 7

Smalltalk has builtin support for Fractional numbers. These compute exact values and thus avoid the usual floating-point rounding errors. Multiplying 1/3 by 9 gives an exact integer 3, not 2.9999999 as in some other languages:

(1/3)*9

Length 8

Scaled Decimal (FixedPoint) numbers are perfect for monetary values. They will print out with the specified number of fractional digits. Technically, they are fractions with a power-of-10 denominator. The following is a fixedpoint constant which always prints itself with 2 digits after the decimal point:

105.12s2

Length 9

In Smalltalk, assignment is done with ":=". The "Value comparison" operator is "=", as opposed to the "Identity comparison", which is "==". The following will assign a boolean true or false to b, depending on the numerical value of x (i.e. works for x being of ANY numeric type, such as Float, Int, FixedPoint etc.)

b:=(x=10)

Length 10

Intervals are collections, and as such can be used whereever other indexable collections can be used. For example, they can be enumerated with the "do:" messsage, passing a block like shown above; i.e. "(1 to:10) do:[:x |...]". The following creates an Interval representing the integer numbers from 1 to 10.

(1 to:10) 

Length 11

In Smalltalk, statements are separated by a period - just like in English. I added a space, to get 11 characters:

a:=0. b:=1.

Length 12

There's no real syntax for method definitions. You can create methods dynamically, but that takes a lot more chars to demonstrate. This is what you could see as a method definition in a class browser:

+ s
^self, s

This is a binary method called "+", that takes an argument "s". And it returns (^) the concatenation of the receiver with the argument.
Define it in class String to instantly uglify the language!

Length 13

This used to be 100 factorial, but that impresses nobody...

999 factorial

Open a browser, type it in and print it (alt p in Squeak/Pharo), don't be scared. I wonder if it's right though? Probably is...

Just to be sure:

999 factorial / 998 factorial

Squeak says it's 999

\$\endgroup\$
4
  • \$\begingroup\$ Please add a factoid that tells something about the language. \$\endgroup\$ Commented Jan 27, 2015 at 16:19
  • 2
    \$\begingroup\$ The entire Smalltalk language spec fits on a single sheet of paper (5 keywords). \$\endgroup\$ Commented Jan 27, 2015 at 18:44
  • 4
    \$\begingroup\$ Are you going to add snippets now? \$\endgroup\$
    – Scimonster
    Commented Feb 4, 2015 at 8:42
  • \$\begingroup\$ Also, about length 11, in Smalltalk period separates sentences. In English period ends them. It's a bit of pedantry, but it's the same difference between C and Pascal, for instance (where it's more relevant) \$\endgroup\$
    – fede s.
    Commented Apr 4, 2016 at 19:19
24
\$\begingroup\$

Ceylon

Factoid

The Ceylon name is a play on the Java name (since it is a JVM language, and like many others, it secretly hope to be a better Java). Java and Ceylon (now Sri Lanka) are both islands in the Indian Ocean, one growing mostly coffee, the other growing mostly tea...

Length 1

;

Semi-colons are mandatory in Ceylon, unlike several modern languages. As said in the language FAQ, it is a compromise in syntax.
Note in that languages where semi-colons are optional (JavaScript, Scala, Lua, etc.) but where lines can be split arbitrarily, there are often cases where missing semi-colons can result in ambiguous or unexpected expressions...

Length 2

4T

is a valid literal number in Ceylon. It reads "four tera" and its value is 4_000_000_000_000. Ceylon supports, like Java, digit grouping, and unlike lot of languages, number suffixes from f (femto, e-15) to P (peta, e+15).

Length 3

A|B

is a type which is the union of two disjoint types. This means that the value with this type can be of either A or B type. Since Ceylon does not support method overloading, it allows to define methods accepting various inputs in the same parameter, or various outputs. This feature is great to indicate a value can be null (it can't by default) and to support JavaScript dynamic types.

Length 4

{C*}

Type annotation for a stream of instances of the class C. This stream can be evaluated lazily. That's actually a shortcut for the Iterable<C> type.

Length 5

value

Ceylon is strictly typed, but is able of type inference, ie. you don't have to specify the type of a local variable (or of the return value of a local function) if the compiler can infer it.
You have to spell it out for class fields, function parameters, etc.
So you can declare a local variable with the value keyword in place of the real type, the compiler will guess its type from its assignment. Note that the term "variable" isn't right here, as it will be immutable (the default of local declarations, you have to declare them variable explicitly to mutate them).
I will continue to use the term variable here, even if they are immutable...

Length 6

Float?

Type of a float variable that might be null. By default, Ceylon values cannot be null. We have to declare explicitly if null is possible in the type of the declaration itself. And then, the Ceylon compiler forces us to check if the value is null. Thus, we can never have a NullPointerException, which doesn't exists in the language! It is one of the rare totally null-safe languages (Rust is another one, with a very different approach).
Note that this type declaration is actually a shortcut for Float|Null, ie. as seen above, the union of Float and of the Null type (which has only one instance: null).
Also note that Float is a class on its own, with methods. It is optimized to the Java float primitive by the compiler, though.

Length 7

Float[]

Type of a sequence of float values which can be empty. It is a shortcut for Sequential<Float> and can be written [Float*], similar to the stream / iterable annotation. The difference is that a sequential can be indexed with the [i] notation, like an array. For the record, a Sequence<T> (or [T+]) is a sequential that cannot be empty. An empty sequential has the type Empty and is noted [], of course.
Note that seq[i] where seq is a Float[] is of type Float? ie. the result can be null, if the index is out of the bounds.

Length 8

a else b

As seen above, if a is of type A? ie. can be null, you cannot use it without checking if it is null. It cannot be done with a == null, Ceylon offers various ways to check this. The code above is one of them: if a isn't null, use its value, otherwise, use the value of b (which cannot be null, of course; we can chain the checks...).

Length 9

\{BULLET}

is a valid Ceylon character: you can put any Unicode name between the braces, like \{CARRIAGE RETURN (CR)} or \{WOMAN WITH BUNNY EARS}.

Length 10

if(is T v)

As we seen, we can define union types, meaning that a variable can have one of several types, eg. Integer or Float (or Byte or... etc.).
If all the subtypes derivate from the same interface, we can use the methods of the parent interface.
For example, if we have ArrayList<String> | LinkedList<String> dualList, we can use dualList.size directly.
To use a method specific to one of the member of the union, you have to be sure it is of the given type. For this, Ceylon offers a mechanism allowing in the same shot to check the type, and to downcast it to the specific type: if (is ArrayList dualList) { Integer capacity = dualList.capacity; } is legal because at this point, the compiler is sure to have an ArrayList.
It is equivalent to Java's instanceof and cast in the same shot, just safer: in Java, you can cast to something else than the type you checked!
Note that is is also an operator (resulting in a Boolean) that doesn't narrow down the type. Boolean b = v is T;

Length 11

"N ``p.n``"

Ceylon has string interpolation: you can embed in a literal string an expression between a pair of double backticks. The value of the expression will replace this placeholder. You can have simple local values, field access as shown, complex expressions or function calls. You can have literal strings (with interpolation too!) inside these expressions.

Length 12

f=(A p)=>-p;

Assigns to the f variable an anonymous function defined with the short syntax (fat arrow). Functions are first-class citizens in Ceylon, they are just objects that can be assigned, passed as parameter, returned from another function, etc.
To fit in the length, I omitted the declaration of f which can be done earlier, for example: A(A) f;
Here, f returns the negation of the p parameter which has the type A.
Notice the usage of the negation operator - which must have been overloaded in the definition of A, which then must satisfy the interface Invertible<A>.
Ceylon doesn't support to define arbitrary operators (unlike Scala, where users can get crazy with this feature... :-)), nor even "true" operator overloading, but it supports operator polymorphism: operators are defined (by name, eg. negated for the unary minus) in specific interfaces (here Invertible) that classes needing these operators must implement (must satisfy, in Ceylon vocabulary).

Length 13

C<out T>(T t)

Declaration-site variance: the class C (the class keyword and the class body have been omitted for brevity) declares, in its definition, its type parameter T to be covariant, so C<Car> is a subtype of C<Vehicle> if Car is a subtype of Vehicle.
Collection interfaces (immutable by default), like List or Set are declared covariants.
Mutable collections must satisfy an additional interface with a contravariant declaration (<out T>), defining methods accepting the given class or any supertype of it: a mutable list of Vehicle must accept adding Cars.
Java is using use-site variance, like List<? extends Car>, defined on each List declaration. It is a bit more flexible but puts the burden on the users of the class, so is more cumbersome.
Since version 1.1, Ceylon also support use-site variance for Java interoperability reasons, but promotes declaration-site variance as the preferred method.
Also note the parameter list of the class: it defines both the parameters of the constructor of the class, and the corresponding fields, in the same shot! No need for these cumbersome this.t = t;...

Length 14

for(n in 0..5)

Ceylon doesn't have the classical C-like numerical for loop. Instead, it supports range definitions, and allows to iterate on them.
Here, n (whose type, Integer, is inferred) will go from 0 to 5, included. We could have written 0:6 instead (start, number of items). A range like 5..0 allows count-downs.
These notations are just syntax sugar for declaring instances of the Range<T> class. We can have ranges of numbers, characters or any other type T satisfying the Enumerable interface.

Length 15

return["",0.0];

Return statement in a function. Here, the type of the return value is [ String, Float ]. That's a tuple, of type Tuple.
A tuple is linked list (therefore a Sequence) which captures the static type of each individual element in the list.
We can then access safely each element by its index: Float v = tuple[1];; the compiler knows the size of the tuple and the type of each entry.
Tuples are a practical / compact mean to return several values from a function, where in Java we must create a Pojo (simple, often internal, class with just fields) for this.
Side note: Ceylon doesn't accept abbreviated, unreadable (IMHO) shortcuts for floats: neither 0. nor .0 are accepted, we must write 0.0.

Length 16

shared T v=T(1);

A variable or attribute of a class (field in Java vocabulary) declaration. The variable is immutable (the default) and has a visibility annotation. Unlike Java fields, attributes (and variables) don't have an implicit default value so they must be assigned at the declaration site (or must be, for attributes, in the parameter list of the class).
Note that T(1) creates a new instance of T with one parameter. Unlike Java, we don't need the new keyword.
shared is an annotation, not a keyword. Declarations are private by default, visible only in the code unit where they are declared: the class they belong to, or the package of the file where they are declared, if they are top-level.
shared extends the visibility to the parent: a shared declaration in a class is visible in the class enclosing this class, if any, or otherwise in the whole package containing the class. If a top-level declaration is shared, it is visible to everything that can see the containing package. If the package is shared, it is visible (and its shared declarations) by other packages in the same module, and by code in other modules which import that module. Works like Russian puppets...
We introduced two concepts: packages are like in Java, folders in a folder hierarchy where the path defines a namespace / visibility unit. They allow to organize code in logical groups. Unlike Java, we must declare packages in a special file named package.ceylon in the package they belong to. That's where we declare if a package is shared (or not, by default). On the other hand, we don't have to declare the package on each file of the folder...
Modules are groups of packages, also declared in their own file (module.ceylon) at the root of the package hierarchy. They must declare a version number, and must import the modules (with their version number) used in code belonging to this module. This allows modularity of the code with fine grained management of the required versions.

Length 17

assert(exists x);

Like in Java, assert throws an exception if its expression is false. But unlike Java, the compiler knows that after the assert statement, the condition is true. Here, the expression checks if x, of type T? (remember: that's T | Null ie. either T or Null), exists, ie. is not null. So the compiler accepts to use x.foo after the assert in the same block, because it known it isn't null.
exists can be used in a if too, if that's unsure. assert is used if the programmer knows for sure (except programming error!) that a variable initially null has been set to a non-null value at this point in the code. So assert is used here as a helper of the type checker of the compiler which hasn't flow analysis...

Length 18

class C(Float f){}

Declares a class and its constructor and its attributes in the same shot: the class' parameters are those of the constructor of the class, which then doesn't need to be defined explicitly. These parameters become attributes (equivalent to Java's fields), so no need for this.f = f, the syntax is streamlined, without boilerplate.
Note that a class can have only one constructor, because Ceylon doesn't support method overloading. Instead, it has parameters with default values (and therefore optional parameters), named parameters, etc.
It also implies that the class has an initializer section, containing a mix of declarations, statements and control structures. The initializer is executed every time the class is instantiated and initializes the state of the new instance of the class.

\$\endgroup\$
4
  • \$\begingroup\$ I used (and will use) some of Lucas Werkmeister's suggestions in my entry. \$\endgroup\$
    – PhiLho
    Commented Jan 26, 2015 at 18:31
  • \$\begingroup\$ Semicolons aren't really optional in JavaScript. Either: you include them and your program does what you want, or you omit them and your program does probably something unexpected. In Scala and Lua, there is no time when semicolons are needed (save Scala C-style for loops); you may use them to group statements on to one line for golf. \$\endgroup\$
    – cat
    Commented May 4, 2016 at 21:14
  • \$\begingroup\$ @cat Lot of people code JavaScript without semi-colons. They just take care of avoiding these cases where they are necessary. In Scala and Lua, you can find similar cases where semi-colons can be needed. AFAIK, in Scala, you can get out by inserting a blank line where the semi-colon is necessary. \$\endgroup\$
    – PhiLho
    Commented May 5, 2016 at 22:31
  • \$\begingroup\$ Those people live dangerously. I also live dangerously, but when I do, I get Segmentation fault (core dumped). :P \$\endgroup\$
    – cat
    Commented May 5, 2016 at 22:40
24
\$\begingroup\$

Powershell

Factoid:

As part of Microsoft's "Common Engineering Criteria" Powershell is designed to provide an automation platform and unify the management experience across all MS Server products. It leverages both the command line strength of a robust shell and the object awareness of the .NET infrastructure.

To handle a highly complex environments the standard naming convention for Powershell commands and functions follow a Verb-Noun structure (ex. Get-Help). This means that in favor of clarity and readability long names are actually encouraged. However because this is a "working admin's shell" there are 2 tools that keep this from being a burden. The first is "tab completion" for commands, parameters, filenames, etc. The second is a robust alias structure, many of these examples will feature aliases.

Length 1

|

Pipe Piping is a common feature in Shells. Powershell improves on this by piping objects instead of strings. So if (for example) a command selecting a file is on the left side of the pipe, then all of the complex attributes {Full path, directory, CreationTime, etc.} of that file are available on the right side of the pipe.

Length 2

gm

gm is an alias for Get-Member which presents the various properties and methods that are available for an object. The most common of usage will be following a pipe. Using gm on a file reveals 24 methods and 21 properties native to the System.IO.FileInfo object type. gm is one of "the 3 things that reveal everything in Powershell" if you know only these 3 things you can use them to discover every function available.

Length 3

gci

gci alias for Get-ChildItem (other aliases are dir and ls). In it's simplest sense gci retrieves the contents of a directory; you can apply filters, selectively recurse, and do everything that the DOS and Bash equivalents can. The real power though is that Get-ChildItem has the ability to navigate "Powershell Providers." Providers exist for Environment Variables, the Registry, Certificates, and VM datastores; meaning that once you connect to the provider you can browse and interact with these abstract environments using familiar command-line navigation and logic.

Length 4

help

help alias for Get-Help, and the second of "the three things that reveal everything". Help reveals structure, syntax, and function. For "professional" cmdlets and modules examples will be included. However help is dynamically aware of what's going on, so even for the most slapped together amateur functions you can use get-help to see the basic parameters and syntax.

Length 5

h |fl

This is the first example that is not just a component but is actually full, complete, and practical in daily usage without any further parameters or modifications.

h alias for Get-History. Session History automatically logs your commands, and you can bring up recent commands with the up arrow. However to get a complete picture of command history use Get-History to present this array of information.

| pipe, in this case we are piping an array of HistoryInfo objects. (note: space before or after a pipe is optional... but it sure makes examples more readable. So this could also be a length 4 example. Working from the command line I tend to insert a space before as an old habit.)

fl is an alias for Format-List. Commands beginning with Format- are display options, no data is manipulated. Format-List accepts the piped input and displays the properties (for each array item) as a separate line. This helps to quickly expose statistics like ExecutionStatus, StartExecutionTime, and EndExecutionTime for each history item.

Length 6

(h)[0]

This is a very simple demonstration of some complex concepts.

h as we've already covered is an alias for the Get-History Cmdlet. This Cmdlet returns an array of objects.

( ) brackets in an expression like this work like in a math formulas, you process what's inside the brackets to get the result before other operations are performed. So by using (h) or (get-history) we are designating that things outside the brackets will not be interacting with the command itself, but with the resulting array.

[0] this shows a way of directly specifying one element within an array, following standard comp-sci usage 0 represents the "first" element in that array. This example returns element 0 of the array returned by (Get-History). This can be useful when you want to systematically retrieve the Nth element of a sorted array, change the Nth letter of a string, or change the Nth octet of an IP address.

Length 7

-Whatif

-Whatif is a "common parameter" enabling a safety routine within Powershell. Get-Help states: "When a cmdlet supports WhatIf, the cmdlet reports the expected effect of the command, instead of executing the command."

So if you have generated a list of files stored in the variable $deletePending and your next step is to run $deletePending | Remove-item if you want to make sure that a typo isn't going to ruin your week you can run a simulation of that command $deletePending | Remove-item -whatif Each simulated step will output a line similar to:

What if: Performing operation "Remove file" on Target "C:\folder\file.tmp".

You can also turn WhatIf on for an entire session if you want to do extensive testing. Most native "danger zone" cmdlets support the WhatIf parameter, and support can be integrated into your custom functions.

Length 8

if(h){h}

This demonstrates the logical flow "IF the statement inside the brackets resolves to a Binary True, then run the statement in the curly brackets." It's important to understand that a Binary True ($true) can be achieved in multiple ways. Some examples:

if ($True)        if (1 -eq 1)        if (Get-Date)       if ("False")

That last one surprises people sometimes; but it's strong logic, "False" is a valid string and no valid string will ever equal Boolean False ($false).

In the 8 Length demo, the test being evaluated is "does (Get-History) return $False?"

if ( h ) { h } will return $false if you run it in a brand new session, run it a second time and it will return $true because now a history item exists. Being able to evaluate using cmdlets and functions can be very powerful, as long as you understand if and when a $false can be returned.

Length 9

-computer

This parameter exists for cmdlets that support "implicit remoting" (such as get-process, stop-process, get-service, get-eventlog ). Generally speaking if you could do it through the management GUI or some form of WMI request you can now automate it through Powershell Cmdlets.

Length 10

get-acl c:

If you have a file sharing structure then 1 of 2 things is true; either you need to "clean up the permissions one of these days" OR you've automated your standards.

In both cases get-acl and set-acl are better than the tools you've had before.

This is another tool that leverages powershell providers so it's just as easy to work with the ACL of HKLM:\Sofware\ExampleSoft as it is with C:\Program Files\ExampleSoft. Build a few scripts around the custom installs in your environment and you'll never grant "Local Admin" to a user again.

Length 11

Get-Content

"Gets the content of the item at the location specified by the path, such as the text in a file. It reads the content one line at a time and returns a collection of objects , each of which represents a line of content."

Any good shell better be able to read a file's contents, so why is Get-Content worth mentioning?

-encoding  -raw  -stream  -delimiter  -readcount  -totalcount  -tail

Examining the parameters we see it can do a lot more than just push stdin to stdout. For example we can pull the elusive Zone ID from the alternate data stream to see whether $file is flagged as originating from a trusted or untrusted zone.

Get-content -path $file -Stream Zone.Identifier

Length 12 - modular function component 1

function f{}

Creates a function named f. Code within the curly brackets will be run whenever f is called.

In case you're wondering, since this is an empty function evaluations of f will find it equals $false.

Length 13 - modular function component 2 (updated)

{my original length 13 was actually 12, so I'm re-working this entry}

$MyInvocation

This automatic variable exists for functions and other script blocks. It contains valuable diagnostic information about how a script block was invoked, including arguments and pipeline status.

If we simply place $myinvocation into our function, calls to f will return the invocation properties.

Length 14 - modular function exploration1

$a=1..5+8
f @a

Running this will return the invocation properties from our function, which you can use to verify the breakdown I'm providing here.

This demonstrates populating a variable, and then calling our function with that variable as an argument. Since the ';' represents a break in the pipeline this can also be written as $a=1..5+8;f @a

$a = creates (or overwrites) the variable a

1..5 populates $a with the numbers starting at 1 and ending at 5 (meaning that $a has actually become an array of integers).

+8 looks like math, but since we're working with an array of integers this is really adding the integer 8 to the existing array

f since we defined 'f' as a function earlier we can now call it anywhere within the session just by using its name. Best Practice is to name functions following the Verb-Noun convention. Since function names are automagicly candidates for tab-completion do yourself a favor and only use short function names for silly things like code-golf.

@a Here the space separates the function name from it's arguments.

The @ (array identifier) is interesting. If we call f $a then we pass the array as a single argument. By specifying f @a we pass each individual array element as an argument. The function will behave as if called like this f 1 2 3 4 5 8

Length 15 - modular function component 3

$args| %{$_+$_}

If you ran the "Length 14" exploration code you'll see the "UnboundArguments" invocation property, the $args automatic variable contains an array of arguments passed to a function as undeclared parameters.

% is an alias of Foreach-Object, which accepts the piped object and individually submits each element to the following script block { }

$_ contains the current object in the pipeline context.

$_ + $_ since we are in a foreach context our current object is each individual integer in our array, we demonstrate that by adding each Integer to itself. Since the + operator is context aware it reacts appropriately to either integer or array contexts.

Current Module:

Function f{
$myinvocation
$args| %{$_+$_}
}
\$\endgroup\$
2
  • \$\begingroup\$ now that you're at 12 you can show superfluous while loops! h | % { $_ } \$\endgroup\$
    – KutuluMike
    Commented Jan 29, 2015 at 23:21
  • \$\begingroup\$ @MichaelEdenfield nah, all those spaces are optional :-) You mean h|%{$_} which is a 7 length. And I'll need 15 to do h|%{$_}|? -p id \$\endgroup\$ Commented Jan 30, 2015 at 13:57
24
\$\begingroup\$

Go

Go, also commonly referred to as golang, is a programming language initially developed at Google in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a statically-typed language with syntax loosely derived from that of C, adding garbage collection, type safety, some dynamic-typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library.

Link for myself, or anyone who wants to contribute to this answer.

Length 14

var x [9]int32

This is an example of how to create an fixed array. You can access it use normal indexing operation x[8] for example. You can iterate any array or slice using for-range statement, for example:

for index, value := range x { // value == x[index]
}
for index := range x {
}
for _, value := range x {
}

Length 13

var x []int32

This is a longer example of slice, slice is a struct that stores current length, capacity and pointer to an array. to get the capacity you can use cap(x), to get the current length of the slice, you can use len(x) function. To add an element to the last element you can use x = append(x,data) function, if capacity equal to the current length, it will copied to another array, and the slice points to that new array.

Length 12

var x *int32

This is an example of pointer variable, a pointer most useful to change a value that declared outside function, for example:

func SquareIt(n *int32) {
  v := *n
  *n = v * v
}

This function would multiply a variable passed into it (you must prefix with & when passing non-pointer into pointers), for example:

y := int32(12)
SquareIt(&y)
fmt.Println(y) // 144

A pointer also can be used to change function owner's member, for example:

type Person struct {
   Age int
}
func (p Person) Aging1() { p.Age += 1 } // doesn't change the age
func (p *Person) Aging2() { p.Age += 1 } // change the age
func main() {
  me := Person{Age:28}
  me.Aging1() 
  fmt.Println(me.Age) // 28
  me.Aging2() 
  fmt.Println(me.Age) // 29
}

Length 11

interface{}

This is an example of a type that can hold anything. The interface{} translates to "any type that implements at minimum 0 function". Here's better use-case on how to use this keyword

type Stringer interface {
  String() string
}

That snippet above means that Stringer is a type that could hold anything that already implements String() string function (function named String that returns a string), for example:

type Hooman struct {
  Name string
  Age int
}
func (h Hooman) String() string {
  return "I'm a hooman named " + h.Name + " " + strconv.Itoa(h.Age)
}
func main() {
  me := Hooman{}
  me.Name = "kis"
  me.Age = 28
  x := Stringer(me)
  fmt.Println(x.String()) // kis 28
}

Length 10

func X(){}

This is an example of how to create a function. This function named X that holds zero parameter and doesn't return anything. You can add parameters/arguments between the () and return type between the ){, for example:

func Add(a int, b int) int {
  return a + b
}

Or alternative syntax:

func Add(a, b int) (c int) {
  c = a + b
  return
}

A function can have its own owner, this function often called method in another language, to set the ownership of a function, just type the owner between func and the function name, for example

type Person struct {
  Name string
  Age  int
}
func (p Person) Print() {
  fmt.Println("I'm a person named " + p.Name)
}
func main() {
  me := Person{"kis",28}
  me.Print()
}

Length 9

package X

This is an example of the first statement that you must type to create a package/library. The library would be called X, all function, type, constants or variables that declared capitalized, can be accessed from another package by typing X.The_name_of_the_function_or_type_or_constants_or_variables after including the package folder using import keyword. Normally the folder name is equal to the package name, visit here for more information about code organization.

Length 8

[]int{3}

This is an example on how to create a slice that points to an array that contains an element with value 3. To increase the slice you may want to use append function, for example: x := []int{3}; x = append(x,7), now that slice will point to an array that have a value of 3 and 7, that equals to []int{3,7}, to get the length of that slice, use len function, to get the capacity of underlying array, use cap function.

Length 7

strconv

This is the name of standard library that useful to convert mostly anything from/to a string, for example:

package main
import `strconv`
import `fmt`
func main() {
  fmt.Println(strconv.Itoa(1234) + ` is a string now`)
}

Length 6

struct

Struct is a keyword to create a record or a new data structure, that compose another type, this is an example of how to create a new type called Person

type Person struct {
  Name string
  Age  int
}

Length 5

[]int

This is an example of slice data type, slice is a struct that have pointer to real array, a current length of the slice and capacity of that array. Slice is just like a microscope that shows only a part or whole of original array.

Length 4

x:=3

This is an example for a shortcut to create a variable named x and initialize it with int value of 3. The longer version to do the same thing is: var x int = 3. There's no need to add semicolon at the end of each statement.

Length 3

1.2

This is an example on how to create a float constant with float32 or float64 depends on the context.

Length 2

``

Backquote is the string literal, inside those quote could be almost anything (including newline) except the backquote itself.

Length 1

1

This is the example of number literal, this number could be anything, rune (character), uint8 or byte, int8, uint16, int16, uint32, int32, uint, int, uint64 int64, float32, float64 depends on the context, the default is int.

Factoid

Gopher (the mascot of go programming language) is a real animal (rodents family).

\$\endgroup\$
24
\$\begingroup\$

PostScript

Factoid

PostScript is a language designed for printer rasterization engines. It is nonetheless a mostly feature complete programming language based on stack manipulation. This makes it relatively easy to extend the drawing primitives.

PostScript can be executed by many devices, and programs. Aside GhostScript, if you include a encapsulation header, you can use programs such as Word, Illustrator, Indesign as preview (possibly live if you link the file) for your code. This means that surprisingly many users even on the Windows platform can execute your program with no extra installation.

One char snippet

2

Puts the number 2 topmost on your execution stack. Nothing fancy done with this yet, but hey, we have allocated some memory.

Two char snippet

==

Print and remove topmost item in stack to stdout. Since not all systems are guaranteed to have a meaningful stdout this may in fact do nothing. Raises an error if stack is empty.

Three char snippet

(a)

Push a string containing a to the stack.

Four char snippet

save

Save the state of your virtual machine and put a save object on top of your stack. You can then use restore on this object to return to the global saved state at any time.

Five char snippet

5 sin

Calculate the sine of 5 degrees. Postscript quite universally thinks of angles as degrees, as opposed to more mathematical radians of many languages use.

Six char snippet

moveto

When executing drawing instructions, PostScript acts like a plotter (or pen in hand). The moveto command moves the virtual pen to a location specified by the two topmost items on the stack; topmost being the y direction and the second the x direction.

Seven char snippet

1 2 add

And finally we have enough chars to actually compute something trivial. Here we push 1 and 2 to the stack. Calling add then pops them both, adds them together, and pushes the sum onto the stack. Leaving 3 on top of the stack.

Eight char snippet

/v 9 def

Define symbol v as 9. This is mostly equivalent to doing v = 9 in most other languages. So now the previous example could look as v 2 add and it would result in 11 in the stack.

Ten char snippet

0 2 8{}for

A for-loop. Normally you'd add spaces around the function {} but I'm running out of chars. This produces numbers even numbers 0 through 8, as the stepping is 2. So the stack after this would be 0 2 4 6 8. 20 more chars and we can start drawing stuff. (not a good language for golfing)

Eleven char snippet

/a {add}def

Simple function definition; the function goes between the curly brackets and acts upon the stack. Note how it uses same mechanism as snippet 8. Now you could write the 7 char snippet as 1 2 a.

Twelve char snippet

4 3 gt{1} if

So here you go some flow control, if 4 is greater than (gt) 3 execute function {} which in this case deposits 1 in the stack.

Thirteen char snippet

0 0 6 0 5 arc

Make a 5 degree arc with a radius of 6 at the origin (0, 0). Note this does not actually draw anything yet; it prepares for drawing by constructing something that's called a 'user path'.

Fourteen char snippet

20 0 translate

Changes the transformation matrix so that your drawings are henceforth positioned 20 units more right. This is useful if you want to repeat the same drawing routine in different places. PostScript coordinates are measured from the bottom left corner of your drawing surface and each unit is one PostScript Point (a unit Adobe invented) that is 1/72 of an inch.

Eighteen char snippet

1 1 5 5 rectstroke

Draws a stroked rectangle onto the canvas in the lower left corner of your page.

Twenty-one char snippet

4 4 moveto 2 5 lineto

Puts a line segment into the drawing buffer.

\$\endgroup\$
4
  • \$\begingroup\$ @mbomb007 Edit appreciated \$\endgroup\$
    – joojaa
    Commented Jun 24, 2015 at 8:23
  • \$\begingroup\$ Need one more number for x y radius ang0 ang1 arc -. I only noticed this because I've implemented arc. \$\endgroup\$ Commented Jan 14, 2016 at 6:03
  • \$\begingroup\$ When you get to 19, you can 0 0 1 1 rectstroke. \$\endgroup\$ Commented Jan 14, 2016 at 6:39
  • \$\begingroup\$ @luserdroog right you are will fix as soon as i have a computer in front of me. \$\endgroup\$
    – joojaa
    Commented Jan 14, 2016 at 9:22
24
\$\begingroup\$

QBasic

The programming language that everybody grew up on[citation needed]--at least, everyone who grew up with MS-DOS during the 90s.

Factoid

QBasic is actually an interpreter and an IDE together. When you enter code, the QBasic editor automatically formats it for things like whitespace and capitalization. The QB64 emulator, which I'm using to test my programs, gives the option of turning auto-formatting off, allowing a few nice golfing shortcuts in an otherwise fairly verbose language.

Length 1

1

This is a valid QBasic program--but only because QBasic allows line numbers. The above is therefore an empty statement (on line number 1), which does nothing.

Length 2

?a

Lots of stuff going on here:

  • ? is a shortcut for PRINT.
  • a is a variable. Since it doesn't have a type suffix and hasn't been declared with DIM, it is numeric; so it is auto-initialized to 0.
  • Thus, this program is basically equivalent to PRINT 0. But because QBasic is optimized (?) for outputting numeric data in tables, what it actually prints is 0 . (The leading space is so 1 and -1 will line up properly, and I suspect the trailing space is so that printing multiple numbers in a row won't result in something like -1-2-3.)

Length 3

CLS

QBasic doesn't use an output stream like C-based languages; instead, it uses a cursor to write stuff to a window (see snippet 13 for more on that). The DOS implementation doesn't clear the window between runs, so it can start to get cluttered after a while:

 0 
 0 
 0 

--which is why most QBasic programs have the CLear Screen command somewhere near the beginning.

(The QB64 emulator starts over with a blank screen each time you run your program, which I find just a little disappointing.)

Length 4

BEEP

Does just what you think it does.

What I like about QBasic is that it has fun commands like this built into the syntax, whereas other languages usually require external libraries or weird workarounds. In Python, for example, the quickest way to get a beep is the extremely cryptic print("\a"); but that doesn't even work in all environments (in particular, the IDLE shell that comes with Python prints a bullet character instead).

Length 5

?2^42

^ is exponentiation, of course. (Don't know what possessed C and its derivatives to use it for bitwise xor.)

Despite the fact that this looks like integer math, we don't get an overflow. The default numeric type in QBasic is actually SINGLE, which is a floating-point number that shows (up to) seven significant digits. If the fractional part is zero, it will display as an integer: for example, PRINT 1.0 outputs 1. The result above has more than seven significant digits, however; so we get it in scientific notation as 4.398047E+12.

Annotating one of the operands with the # suffix would coerce the expression to DOUBLE precision, giving up to fifteen significant digits: ?2#^42 gives 4398046511104.

Length 6

?1:RUN

Our first multi-statement program! : is a statement separator.

The RUN command can be used in a few different ways. If you give it the name of another QBasic source file, it will switch execution to that program. If you give it a line number in the current program, it will restart the program at that line. (This is different from a GOTO because all variables are cleared, as if starting the program from scratch.) And if you don't specify an argument, it will restart the program from the top. The code above prints 1 infinitely.

If you don't want the 1s on their own lines, you could use ?1;:RUN--the semicolon suppresses the newline when printing. But that will actually give you 1 1 1 ... (see the length-2 snippet for why). To fill the screen with 1s, you'd need to use a string: ?"1";:RUN.

Length 7

INPUT x

The INPUT statement by default displays a ? prompt and waits for the user to enter a value. Lacking a type suffix, x is a single-precision numeric variable, so anything like 3.14 or -42 is valid input. What happens if you try to enter something that's not a number?

? Jabberwocky
Redo from start
? 

It's a bit cryptic, and it can royally mess up the alignment if your program is using some kind of text-based user interface, but at least the program doesn't crash, interpret the input as 0, or anything weird like that. ;^)

Note: QB64 doesn't even let you type invalid characters when an INPUT statement asks for a number.

Length 8

PLAY"CF"

Music is yet another feature awesomely built in to QBasic. This code plays two quarter notes (middle C and middle F). A PLAY string has ways of changing the octave, playing sharps and flats, changing the duration of notes, and so much more!

Length 9

SCREEN 12

Different SCREEN modes in QBasic allow for different graphical capabilities: various resolutions, color vs. black-and-white, text-only or graphics-capable. Historically, these were included to account for differences among display hardware. The default mode, SCREEN 0, is text-only, so any program with graphics in it has to start with a SCREEN statement. (Pretty pictures later if I get more votes!)

Length 10

?4*ATN(1#)

Would you care for some pi? QBasic has a good number of math functions built in, ArcTaNgent among them. The # type annotation is used here to make the resulting value DOUBLE, so we get more digits: 3.141592653589793.

Length 11

COLOR 2:?42

Time to get colorful.

Green 42 (Shown 2x actual size)

In the default SCREEN 0, QBasic offers 16 foreground colors:

The 16 colors in QBasic

Each color 8-15 is a lighter version of the corresponding 0-7 color. The darker colors 0-7 are also available as background colors, and adding 16 to a foreground color makes it blink! (See this thread, particularly the bottom post, for a great historical explanation.) So, since a COLOR statement affects everything subsequently printed, we can write this:

COLOR 25,4

and see this:

Blinking "Press any key"

Trippy.

Length 12

DRAW"F3U7R9"

The DRAW command takes a string of codes and draws stuff on the screen. As a graphics command, it cannot be used in the default screen mode, so you'll need to combine this snippet with snippet 9 in order to run it. This example goes 3 pixels diagonally down and right, 7 pixels up, and 9 pixels right, for a tiny square root symbol:

QBasic DRAW command--square root symbol (Shown 2x actual size)

Length 13

LOCATE 7,8:?9

Recall (from snippet 3) that QBasic outputs text to a window, not an output stream. The LOCATE command allows you to set the cursor location for output. So if you want to display something halfway down the screen, you don't need to print a bunch of newlines first--just LOCATE to the right row and column.

Using LOCATE command

Importantly, this doesn't affect any other text on the screen (except when directly overwriting it), which makes QBasic very straightforward for creating textual user interfaces--or dungeon games. Most languages would have to use control codes or a library like curses.

Length 14

GOTO a
?1
a:?2

What would QBasic be without GOTO? The much-maligned feature is alive and well here, allowing arbitrary jumps in program flow to defined labels. The above snippet, of course, skips to the third line and outputs 2.

A label must come at the beginning of a line. It can be any identifier followed by a colon; or, it can be a BASIC-style line number, sans colon.

While it is true that 1) most uses of GOTO can be replaced by conditionals or looping constructs and 2) those that are too complicated for this treatment are probably a bad idea to begin with, I still like GOTO, for a couple of reasons. First, it's how assembly works under the hood, so learning it first in QBasic is valuable practice. Second, I still think it's more readable (and less redundant) to write code like this:

getNumber:
INPUT x
IF x = 0 THEN PRINT "Enter a nonzero number": GOTO getNumber
PRINT "The inverse is"; 1/x

than the Python equivalent:

x = float(input())
while x == 0:
    print("Enter a nonzero number")
    x = float(input())
print("The inverse is", 1/x)

Length 15

RANDOMIZE TIMER

QBasic does (pseudo)random numbers via the RND function, which is normally invoked without arguments and returns a random number in the range [0, 1). However, you'll get the same sequence on each run of the program unless you seed the PRNG with the RANDOMIZE statement. The usual seed is TIMER, which returns the number of seconds since midnight. This provides a different seed on each run of the program... at least, if you don't run it at exactly the same time each day.

If you do want the same numbers each run (maybe for testing purposes), you can pass a constant to RANDOMIZE--or just put RANDOMIZE without specifying a seed, in which case you'll be prompted when you run your program:

Random-number seed (-32768 to 32767)? 

Nobody can say QBasic isn't user-friendly.

Length 16

CIRCLE(9,9),8,,2

Graphics command: combine with snippet 9 to run.

QBasic's drawing commands are interesting because they each have a unique syntax, tailored to make the most sense for the particular command. The syntax for CIRCLE is CIRCLE (x, y), radius[, options]. (If you think that's odd, just wait till we get to see LINE in snippet 18.)

The first option to CIRCLE is color: we could have drawn a green circle with CIRCLE(9,9),8,2. But we've got an extra character to play with, so let's leave the color option blank (defaulting to white) and look at the next option. This happens to be startRadian. A value of 2 means that instead of a full circle, we get an arc of 2π - 2 radians:

Arc of circle (Shown 2x actual size)

(Note that this apparently follows the standard quadrants system, despite the fact that QBasic has the origin at the top left with the positive y-axis pointing down.) The remaining CIRCLE options are endRadian and aspect, which allows you to draw ellipses:

CIRCLE(51,26),50,,,,0.5

Half-squashed circle

Length 17

LINE INPUT s$:?s$

Reads an arbitrary line of text from the user and echoes it back.

What's important here is the word "arbitrary." The reason for the existence of LINE INPUT is that the regular INPUT command can't read commas. It treats them as field separators, so you can get two strings in one go by doing INPUT a$, b$. (Also useful for reading comma-separated data from a file.) But what if your input contains commas? Well, you can wrap it in double quotes and it'll treat the comma as part of the string. But what if your input also contains double quotes? That's when you need LINE INPUT, which simply reads everything until you hit enter.

Length 18

LINE(1,1)-(9,9),,B

Graphics command: combine with snippet 9 to run. Draws a line from (1,1) to (9,9), right? Well... not exactly.

It's a box! (Shown 2x actual size)

This would create a diagonal line, except that we've also specified the B option for "box." So instead of a line, we get a rectangle. There's also BF for "box, filled." (As in snippet 16, the empty space between commas is for the unused color argument.)

I'm actually a fan of this unusual syntax, whenever it makes sense for the given command. I find that it's a mnemonic aid. Contrast the above with a function that takes a gajillion* positional arguments--you can never remember which one is which--or half a gajillion keyword arguments--you 1) have to remember the names of the keywords and 2) can end up with a pretty long line of code if you use multiple arguments. (I know the counterarguments; I'm just saying that this is something I enjoy about QBasic.)

* Slight hyperbole.

Length 19

?0:PAINT(10,4),9,15

Graphics command: combine with snippet 9 to run.

PAINT takes a starting point, a fill color, and a border color. It does a flood fill until it hits border-colored pixels or the edge of the screen. It's typically used to fill circles, rectangles, and other graphics figures. But hey, printed text is just pixels on the screen too:

0 donut filled with blue(berry) jelly (Shown 2x actual size)

Length 20

?ASC(INPUT$(1));
RUN

INPUT and LINE INPUT aren't the only ways to get input in QBasic. The INPUT$(n) function reads n keypresses and returns them as a string. (It can also be used to read from a file or a serial port.) INPUT$ does not display a prompt or echo the characters to the screen as they are typed. It therefore has a myriad of uses, from password entry to the famous "Press any key to continue."

The above program waits until the user presses a key, prints the ASCII code of that character, and loops infinitely using RUN (see snippet 6). Entering ABC123<esc><cr><tab><bksp> will result in output of

 65  66  67  49  50  51  27  13  9  8 
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I know this is old, but I gave you the 13th upvote, and I'm interested in seeing what you can do with 13 characters (you mentioned it in your length 3 snippet). I grew up on QB45 and absolutely loved it. \$\endgroup\$ Commented Mar 31, 2016 at 19:28
24
\$\begingroup\$

Scratch

Oops! I kind of feel like a terrible person for not updating this lately. I'll try to be more consistent with my updates, e.g. when somebody votes I'll update.. Forgive me? :)
Oops! Wow, did it again. A link or two was broken; that should be fixed now.


Scratch is a graphical programming language created by MIT. Because it's graphical and block-based, rather than counting the number of characters, I'm going to count the number of blocks (after all, the number of characters could change with translations).

Rather than getting a screen shot of every single script I'll give you a link to a Scratchblocks page. I'll also post the code for it below.

This answer is in development! ;)

Um, also, maybe read the scripts from bottom to top..? :P


Length 11

Code:

when [space v] key pressed
set [Playing? v] to [1]
set [Score v] to [0]
reset timer

when this sprite clicked
if <(Playing?) = [0]>
  change [Score v] by [1]
end

when [timer v] > (10)
set [Playing? v] to [0]

Well, we've got three whole scripts here! This should be simple enough to understand, but I'll explain it anyways.

when [space v] key pressed
set [Playing? v] to [1]
set [Score v] to [0]
reset timer

When the space key is pressed, we want to set the playing variable to 1 (e.g. true), the score variable to 0 (e.g. no points yet), and reset the timer. The timer is an important part of this project!

when this sprite clicked
if <(Playing?) = [0]>
  change [Score v] by [1]
end

When the sprite is clicked on, if we are currently playing, change the score by 1.

when [timer v] > (10)
set [Playing? v] to [0]

When the timer is greater than 10 (e.g. 10 seconds have elapsed since the timer has last been reset) set the playing variable to 0. Because it is now 0, in the when-sprite-clicked script the score is no longer increased.

By the way, here is the costume that the sprite uses:

Sprite Costume

A key bit of information about this project is that you can have multiple scripts inside a single project. Each of these scripts will be called according to their hat block, so when this sprite clicked will happen when this sprite is clicked on!

Getting a bit technical here, but Scratch does not use multiple threads. Instead you should think of scripts being stuck into a list of things to do. It's a bit complicated but works similarly to the way JavaScript does.

Also, keep in mind that many blocks will automatically update the screen (as well as control events, for example, a loop looping) and will tell Scratch's interpreter to go on to the next script occurring simultaneously. You can get around this by putting your script inside of a run-without-screen-refresh custom block as shown in length 8.

Length 10

Code:

when GF clicked
set tempo to (pick random(30) to (120)) bpm
set [Note v] to [55]
repeat (3)
  play drum (15 v) for (1) beats
end
repeat (10)
  play note (Note) for (0.3) beats
  change [Note v] by [1]
end

This one hopefully won't blow your mind too much. It's a simple melody with a drumroll. I don't think it needs that much describing. ;)

(Scratch Official Editor) (Scratchblocks) Length 9 Snippet:

// Sprite: Cat
when GF clicked
go to x: (-130) y: (90)
point towards [Apple v]
repeat until <touching [Apple v]>
  move (2) steps
end
broadcast [got apple v]

// Sprite: Apple
when I receive [got apple v]
hide

What's so nice about Scratch is that it's scripts are very self-explanatory. I probably don't even need to explain to you what this does for you to figure it out (especially if you run the program by going to the above link).

However, this example does introduce a few new things I haven't shown yet:

  • Sprites: These are Scratch's idea of things in the world (stage). A sprite is generally what you use when you want to add a character to your scene. Whenever you open up the editor, you already get pre-loaded a sprite - it's that scratch cat! You can use as many sprites as you want in your program as well. Learn more about Sprites and how to create them on the wiki.

  • Broadcasts: A broadcast is as it sounds (literally) - it's a message that is sent through the project to every single sprite in the program. You use the when I receive hat to make something happen when a script is broadcasted. Broadcasts are a very important part of the programming language and you can learn more about them on the wiki here.

One last cool thing about this project is that if you change the numbers in the go to x: y: block it will always work - so why not try it?

(Scratchblocks) Length 8 snippet:

when GF clicked
insta

define insta
pen down
repeat (360)
  turn cw (1) degrees
  move (1) steps
end
pen up

Boom - custom procedures! I'd just like to clarify here - this is an instant custom block, or as I and some friends like to call them, atomic procedure. All that means is the block runs in a single frame - which is quite important for turtle graphics!

Here is a screenshot of the script, and the dialog I used to make the custom block:

Atomic Functions

(Scratchblocks) Length 7 snippet:

when GF clicked
ask [Hexadecimal decoder - please type a hex number WITHOUT THE 0x PART:] and wait
say (join [] ((join [0x] (answer)) - (0)))

Oh, hey! Scratch has hexadecimal decoding support! Who would have guessed?* Simply use ((join [0x] [###]) - (0)) to decode some hexadecimal.

(Scratchblocks) Length 6 snippet:

when GF clicked
set [var v] to [0]
repeat (10)
  change [var v] by (1)
  say (var) for (0.5) secs
end

Variables in Scratch are represented by their own orange blocks - to declare one, you press the button Make a variable inside the Data category. This creates a new block, name, in the Data category. To manipulate it, use the variable blocks. All variables also have an (optional) watcher which can be customized - see the watcher's wiki article for more information!

(Scratchblocks) Length 5 snippet:

pen down
clear
repeat (180)
  move (2) steps
  turn cw (2) degrees
end

Here we demonstrate - like all good programming languages should be able to - turtle graphics! Just because Scratch is a visual programming language really gives it just that extra bit of fun when you're programming, even more so with the pen!

(Scratchblocks) Length 4 snippet:

forever
  play note ((timer) mod (50)) for (0.5) beats
end

Scratch has many built in instruments - the simplest way to play a note is via the play note for beats block. Keep in mind the default instrument is 1 (piano) and the default tempo is 60bpm. Using blocks found in the Sound Category you can do things like change the instrument, play sounds you import, and even use the built in drum set!

(Scratchblocks) Length 3 snippet:

when [space v] key pressed
point towards [mouse-pointer v]
move (10) steps

When the space key is pressed, it moves the selected sprite toward the mouse. This makes it easier to demonstrate moving towards the mouse as you don't need to move the script whenever you want to change direction (and it would still only be able to go towards the east edge of the stage).


(Scratchblocks) Length 2 snippet:

point towards [mouse-pointer v]
move (10) steps

When the script is clicked, it moves the sprite ten steps towards the mouse when clicked.

(Scratchblocks) Length 1 snippet:

move (10) steps

When the script is clicked, it moves the sprite ten steps (pixels) in the direction it's facing, which, assuming you're using a non-touched-so-far sprite, will be towards the right (90° in Scratch).


Factoid: Scratch was originally released in 2007 (it was made in very early stages in 2003 or 2002 I believe) and now has over 7 million people using it (Scratchers) and over 10 11 million projects created. It's used all around the world as well. Check out the statistics page to see more stats about Scratch, and try it out online here. It's free!

* The Advanced Topics would. :)

\$\endgroup\$
11
  • \$\begingroup\$ Added the second. \$\endgroup\$
    – Nebula
    Commented Jul 17, 2015 at 9:52
  • \$\begingroup\$ Added the third. \$\endgroup\$
    – Nebula
    Commented Jul 21, 2015 at 10:01
  • \$\begingroup\$ oops I suppose I should update this \$\endgroup\$
    – Nebula
    Commented Aug 25, 2015 at 19:11
  • \$\begingroup\$ Added the fourth, fifth, and sixth! \$\endgroup\$
    – Nebula
    Commented Aug 25, 2015 at 19:58
  • 1
    \$\begingroup\$ Nice conversation down here in the comments! \$\endgroup\$
    – user60199
    Commented Oct 18, 2016 at 16:06
1
2
3 4 5
9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.