552
\$\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
    Jan 4, 2023 at 1:43

241 Answers 241

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

The Lambda Calculus

Factoid:

The lambda calculus (specifically, the untyped lambda calculus) is, according to Wikipedia, "a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution." It was published by mathematician Alonzo Church, of whom Alan Turing was a student, in 1936, and is equivalent to a Turing machine—that is, any problem solvable with an algorithm can be solved with this system.

The lambda calculus consists entirely of functions of one parameter. In its pure form, these functions are unnamed, but for ease of understanding, they are often given names like plus and equals. Most[citation needed] modern languages, including Python, C#, and Java, support these anonymous functions.

Length 1:

x

The variable x. A variable is the simplest example of a lambda term, or a valid lambda expression. Note that a variable need not have a type (in fact, must not in the untyped lambda calculus, as types do not exist [hence, untyped]).

Length 3:

f x

Application of the function f to the variable x. Note that function application is left-associative, though this can be overridden with use of parentheses.

Length 4:

λx.x

The identity function! This gives a first look at the form of functions. A lambda function consists of two parts: the parameter (the variable between the first λ [lowercase Greek letter lambda] and the first .), and the return value (everything after the first .). In this example, the parameter, x, is mapped to (guess) x, so the identity function returns whatever value it is fed, be it a number, a Boolean, or a lambda term.

This is an example of an inductive rule of lambda terms: if t is a lambda term and x is a variable, then λx.t is a lambda term. In this example, t is the lambda term x, so this rule makes λx.x a lambda term.

Length 4:

λx.y

A slightly less interesting example, this is a function of x that returns y regardless of x's value. Feed it 5? It gives y. Feed it λx.y? It gives y. Since y is a variable and therefore a lambda term, this expression is indeed a lambda term.

Length 5:

f x y

This is application of a curried function, the basis of the computational completeness of the lambda calculus. f is here called on x, returning f(x), a function (this is called partial application—though f takes two parameters, one can create a new function by passing f only one). This new function is then applied to y. Because of the left-associativity of the lambda calculus, this is read as (f(x))(y) instead of f(x(y)).

An example of a use for this form: f maps x to a function that maps y to x+y. This is a change through currying of the basic addition function; instead of writing plus(x, y), we write plus(x)(y).

Length 7:

λx.λy.x

Finally, something interesting! This function of x returns not a value, but another function! The return value is λy.x (which is effectively identical to λx.y above), so this expression takes an argument x and returns the constant-value function that returns the given x.

This function has some interesting behavior in conjunction with certain others, very similar to that of the Boolean true.

Length 7:

λx.λy.y

Just like the previous example, but it returns the identity function rather than a constant-value one. As you will see soon, this can be made to behave like Boolean false.

This and the previous example are known as the Church booleans.

Length 7:

λf.λx.x

This very closely resembles the Church false; in fact, it is identical, despite the f and x in place of x and y! Through a process called α-conversion, the lambda term λx.R can become the equivalent expression λy.R', where R' is R with all instances of x replaced with y. This is intuitive enough—if f(x)=2x and g(y)=2y, then f and g are equivalent.

The different notation for this function and the Church false is to aid intuition. While the latter takes any two arguments and returns the second, this one is intended to take a function of a value (f) and a value (x). It then applies f to x zero times and returns the result.

With certain other convenient functions, this one can be treated as the number zero. This is an example of a Church numeral.

Length 8:

(λx.x) y

Application of a function again, but this one actually does something, instead of merely serving as a template! The function λx.x is applied to the variable y, done by substituting y for x (the parameter) in the return value, x. This yields y, as one might expect from applying the identity function to y.

This process of replacing each instance of the parameter in the return value with the argument is called β-reduction.

Length 9:

λf.λx.f x

Ooh, something exciting! This looks like the Church numeral for zero, but with f x in place of x. Here, the function f is applied once to x, and this result is returned. We'll call this the Church numeral for one. Noticing a pattern? Yep, the Church numeral for n returns a function of x that returns f applied to x n times.

Length 14:

λa.λb.λf.f a b

This function pairs two values, a and b, creating a function that takes a function parameter f and returns f applied to a, applied to b. These pairs, known as Church pairs, will become very useful later on.

Of course, pairs would be useless without a way of retrieving their elements:

Length 12:

λp.p λx.λy.x

This takes as input a Church pair and returns the first of the pair. Suppose p is the pair (a, b). By the definition of pairs, p applied to λx.λy.x (Church true) is equivalent to λx.λy.x applied to a, applied to b. This returns a.

Length 12:

λp.p λx.λy.y

Likewise, this function returns the second element of a pair. Confirmation of this is left as an exercise for the reader (hint: it's the same as that for the previous snippet).

Length 18:

λn.λf.λx.f (n f x)

Y'know what? Rather than adding a separate snippet for each natural number, why don't we include a recursive way of defining them? This is the successor function, one which takes as input a Church numeral and returns the next.

Here's an example: let's call this function on 1's Church numeral, λf.λx.f x. This gives us (λn.λf.λx.f (n f x)) (λf.λx.f x), which is by α-conversion equivalent to (λn.λf.λx.f (n f x)) (λg.λy.g y) (this is done to avoid name collisions). β-reduction turns this into λf.λx.f ((λg.λy.g y) f x).

Apply β-reduction once more, inside the parentheses, and we have λf.λx.f ((λy.f y) x). Again! λf.λx.f (f x)... Ooh! This looks like what I would expect two's Church numeral to be! How nice.

Another look at the successor function reveals that it is quite intuitive: it takes a Church numeral n and returns another Church numeral, one that returns a function f applied to n applications of f to x—that is, n+1 applications of f to x.

Length 30

λa.λb.a (λn.λf.λx.f (n f x)) b

Spamming successor functions gets tedious. Let's skip all that and define addition! This snippet takes two Church numerals a and b and returns their sum, as a Church numeral.

Of course, we must test this. Note that the outer parentheses contain the successor function exactly; since we already understand that one, let's just call it SUCC now. Our expression becomes λa.λb.a SUCC b.

Let's add two and three (defining TWO as λf.λx.f (f x) and THREE as SUCC TWO). (λa.λb.a SUCC b) TWO THREE is β-reduced to (λb.TWO SUCC b) THREE and again to TWO SUCC THREE. This does PRECISELY what we'd hoped—it applies succession to three two times, yielding two plus three!

\$\endgroup\$
2
  • \$\begingroup\$ By the way, Vote count no-longer restricts how many snippets you can write. \$\endgroup\$
    – ATaco
    Oct 17, 2017 at 22:24
  • \$\begingroup\$ Ah, I missed that. \$\endgroup\$
    – ATaco
    Oct 17, 2017 at 22:25
17
\$\begingroup\$

Retina

Factoid:

Retina is based on regular expressions, and supports various stages like match, replace, split, grep, antigrep, transliteration, and sort.

0 bytes:

Counts chars in input...+1!

1 byte:

1

Counts the number of 1s in the input. Pretty boring, but can make quick unary to decimal conversion.

2 bytes:

.+

Outputs the number of nonempty lines in the input.

3 bytes:

\d

Deletes numbers. (Tip: If you want empty lines to show in code, use <pre> tags.)

4 bytes:

1
$_

Computes squares. (Unary in, unary out)

5 bytes:

T`l`L

UPPERCASES YOUR TEXT.

6 bytes:

G`cats

Finds the [cats]

7 bytes:

\d
$*
1

Sums digits in input.

8 bytes:

^
1
1
$'

Computes triangular numbers. (Unary in, unary out)

9 bytes:

(.)\1+
$1

Dereplicates chars.

10 bytes:

S`.
¶+
$.0

Counts chars in a slightly weird way. (The shortest way is 3 characters.)

11 bytes:

(^x|\1xx)+$

Matches squares.

14 bytes:


\(*S1`
\(*S1`

The shortest Retina quine.

15 bytes:

1
$`$'2
2
$_1
1

Computes cubes. (Unary in, decimal out)

\$\endgroup\$
5
  • \$\begingroup\$ A few corrections: O`. sorts all the non-linefeed characters of the input, even across lines. S.+` is a split stage which means it doesn't count anything but gives you a string of M + N - 1 linefeeds, where M is the number of non-empty lines and N is the number of lines in total. Also I'm not sure what you mean by "dereplicating chars" but the last snippet just replaces each line with its last character. \$\endgroup\$ Apr 25, 2016 at 10:08
  • \$\begingroup\$ The last example will actually find a match in any input, because it can simply match the end of the string as an empty match. (Of course that still sort of helps to distinguish non-squares from squares.) This could be fixed by either matching positive squares with + instead of * or by prepending ^ to ensure the entire string is matched. \$\endgroup\$ Jun 24, 2016 at 12:26
  • \$\begingroup\$ Your 9 byte program can be written in 3 bytes: D`. \$\endgroup\$
    – mbomb007
    Sep 20, 2016 at 19:32
  • \$\begingroup\$ Nope. xxyyxx. \$\endgroup\$ Oct 15, 2016 at 15:32
  • \$\begingroup\$ .+ only counts non-empty lines. Triangular numbers can be calculated in 5 bytes: Try it online! \$\endgroup\$
    – Neil
    Oct 27, 2020 at 11:04
16
\$\begingroup\$

Elixir

Elixir is a functional, concurrent, general-purpose programming language built atop the Erlang Virtual Machine (BEAM). Elixir builds on top of Erlang to provide distributed, fault-tolerant, soft real-time, non-stop applications but also extends it to support metaprogramming with macros and polymorphism via protocols.

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

Length 8

fn-> end

This is an example on how to create a function, this function only returns nil, to call it, you must assign it to a variable, for example: x=fn->123 end, then call it using .(), such as: x.() that would return 123.

Length 7

[a: 12]

This is example of creating keyword list (list of key-value pair), this statements are equal to [{:a, 12}]. We could access the value using square bracket and the key, for example:

kl = [a: 12, b: 13]
kl[:b] # 13
kl[:c] # nil
kl[:a] = 14        # error!
kl = [a: 14] ++ kl # [a: 14, a: 12, b: 13]
kl[:a] # 14

Length 6

<<65>>

This is an example on how to create a binary, this would result a valid string "A", to concat the string or binary you can use <> operator, for example: "AB" <> <<67,68>> that would end as ABCD

Length 5

{1,2}

Tuple is just like a list, to get the length, use tuple_size function, to get the element on n-th position, use elem function, to change the value of n-th position, use put_elem function. To find more about the difference between lists and tuples, visit this link.

x = {3,"yay"}
elem(x,1)
# "yay"
put_elem(x,1,"wow")
# {3,"wow"}

Length 4

[12]

This is an example on how to create a list, to get the length, use length function, to append with another list, use ++ operator, to remove all first element that exists in another list we could use -- operator. To get the first and last element use hd and tl function. To get the n-th element, use Enum.at, to set, use List.replace_at.

[1, 2, 3] ++ [4, 5]
# [1, 2, 3, 4, 5]
list = [1, 1, 2, 2, 3, 4] -- [2,3]
# [1, 1, 2, 4]
hd(list)
# 1
tl(list)
# 4
Enum.at(list,3)
# 4
List.replace_at(list, 0, 9)
# [9, 1, 2, 4]

Length 3

1/2

This is an example on how to do division, the result is 0.5, to do integer division, use div function, for example div(7,2) or div 7,2 would return 3.

Length 2

?A

Question mark is one way to get the integer (or code-point) value out of a character, for this example it would return 65 as defined in the ASCII encoding.

Length 1

1

This is the example of integer literal, to check whether a variable or literal is integer, we could use is_integer function. There are virtually no limit on how big an integer can be, since it uses bignum as implementation. The limit on the VM in 32-bit platform is 536870911 bytes and 64-bit platform is 2305843009213693951 bytes, the integer creation will fail when the value are larger than those size or when not enough memory.

Factoid

iex is Elixir's interactive shell (REPL). To exit this program, press Ctrl-C twice.

\$\endgroup\$
16
\$\begingroup\$

LambdaMOO

LambdaMOO is a server for running an object-oriented MUD which can be programmed live by the players themselves. The LambdaMOO server handles the telnet connection for each player, reading in what the player types, parsing it and running the correct verb. It also persists all of the objects to a database, meaning you can shut down a server and bring it back up and the environment will be exactly where you left it. (It's much like a smalltalk image in this regard.)

The oldest running LambdaMOO server (up since 1991) is at lambda.moo.mud.org; you can telnet to port 8888 and log in as a guest to look around.

This answer will cover the LambdaMOO programming language (which has no separate name), but will of necessity touch upon other aspects of the LambdaMOO environment, such as the server, players and databases.

Some interesting links if you'd like to learn more:

Factoid

LambdaMOO code is stored as bytecode and decompiled for editing. The original intent was for it to be stored and edited offline, then uploaded to the server. In practice, it turned out to be easier to edit it live on the server, so a decompiler was implemented. The bytecode is expressive enough that this tends not to be an issue, and it has the advantage of enforcing a uniform coding style!

Length 1

;

Like many languages, LambdaMOO statements are semicolon-terminated, and an empty statement is valid. However, it is optimised away by the compiler and won't be there when the program is edited again! (This same compiler optimization also cleans up empty else statements and the like.)

; is also used as a synonym for eval at the beginning a line of user input, allowing programmers to test code without writing an entire verb. (Normally, user input is interpreted as English-like commands such as go west or take the box.)

Length 2

Because it is designed for programming an interactive environment, LambdaMOO objects are persistent and are identified by a unique number. They have two types of data associated with them, properties (data) and verbs (code). Both properties and data are inherited from an object's parents, and can be overridden.

Object numbers are represented as #nnn.., starting from 0 and counting up. The first LambdaMOO server (lambda.moo.mud.org) has been running since at least early 1991 and is up to #124703. It would be a lot further than that if they hadn't implemented object number reuse around 1996. Objects are not usually created and recycled automatically; instead, they are created by players to represent persistent "physical" objects--rooms, players, a wind-up duck, and so on. Because of the "Virtual Reality" design, even objects which wouldn't ordinarily be physical are generally represented as such on a MOO. For instance, the database of player's birthdays is "a computerized datebook shaped like a big birthday cake."

There are two objects of particular interest to be found in every MOO database:

  • #0 is The System Object. It is the only positive object (negative ones will be covered under Length 3) which is treated specially by the server.
    • Various verbs of #0 are called by the server when events happen, such as a player typing a line, the server starting or stopping, and so on. It is the job of these verbs to handle the event as necessary; thus, the database (and the verbs of #0 defined therein) define most of the behavior of the actual server.
    • Properties of #0 are used for a special syntax for referring to objects globally, without memorizing their object number. If #0 has a property named "foo" set to #1234, $foo can be used anywhere to refer to #1234.
  • #1 is the Root Class, the parent of all other objects. LambdaMOO (like JavaScript) uses prototypal inheritance rather than the more common class-based inheritance. Every object has a parent, from which it inherits any properties and verbs that are not defined on itself. (#1 is the parent of both itself and #0.) #1 defines a few verbs and properties which should exist on every object, such as a name and description, as well as various verbs to handle events such as: creation and recycling; moving things into and out of the object; moving the object into and out of other objects; and handling user input and output.

Length 3

LambdaMOO uses negative object numbers to represent special things which do not actually exist, but which must have an object type so they can be manipulated in the same way as a normal object.

  • #-1 - $nothing - An object which is not. Most commonly seen in the context of object locations: all objects must have a location; objects which don't need to be inside of something else have their location set to #-1.
  • #-2 - $ambiguous_match - Used as a placeholder when the user's input could have matched multiple objects. For instance, "ball" in a room with a "red ball" and a "blue ball" will be represented as #-2 (generally causing a "which did you mean?" error message).
  • #-3 - $failed_match - Used as a placeholder when the user's input couldn't be matched to any object. For instance, "ball" in a room which only contains a "red cube" and a "blue cube". This generally causes an "I see no x here."-type message.
  • #-4 and below are used to represent players who have not logged in yet (that is, they're still at the login screen). These players need an object number so the code can interact with them, but can't be given a positive one because the server doesn't know who they are yet. When I log in, for instance, my connection might be given #-6 until I log in, at which point the connection is re-associated with my actual player object, #124434.

Length 4

verb, dobj, iobj: When the user types in a command, it is split up according to the form verb [direct-object [preposition indirect-object]]. (For example, look, take ball, give ball to Henry.)

direct-object and indirect-object are matched to an actual object (or #-1 or #-2 if necessary) and verb is called on whichever object is found to have a matching one first. (It searches the player, the room, the direct object, and the indirect object, in that order.) That verb can then use the special variable verb to find out what it was called as (equivalent to $0 in a bash script), and dobj and iobj to determine the objects that were matched to the direct and indirect objects. There are also special variables for the preposition, as well as the actual strings (rather than matched objects) for the direct and indirect objects.

Length 5

1?2|3 - This is the syntax for the ternary conditional operator; in most c-type languages it would be 1?2:3 instead. There is no special type for binary values; rather, each possible value for each possible type is categorised as either true or false. True values are ints and floats other than 0 and non-empty strings and lists. Everything else is considered false, including 0, "", {}, and all objects. Thus, 1?2|3 evaluates to 2.

Length 6

player is another special variable (like dobj et al), but it refers to the player object that executed the command. For instance, when I (#124434) type pull lever on contraption, the contraption:pull verb has the player variable set to #124434. This is most commonly used for output: the player has a tell verb which sends a line of text over the correct network connection to the person's computer, so they can read about the antics of the horde of lemmings they have just unleashed on an unsuspecting Barney. (The Rube Goldberg Contraption has to be seen to be believed. Telnet to lambda.moo.mud.org port 8888 and go southeast from the Living Room.)

Length 7

"ab"[2]

Strings are represented with the usual double quotes, and list indexes are done with square brackets. Unlike many languages, lists and strings start indexing with 1 rather than 0. Thus, this expression returns "b".

Length 8

#1:huh() is the shortest verb call I could come up with. Verbs are the same as a method in most other languages; the syntax for calling them is #nnn:verb([arguments...]).

You wouldn't generally call :huh() directly; it is called by the default core when a player tries to do something to an object that the object doesn't support. For instance, globnitz ball will look up ball (say it's #1234), discover that #1234:globnitz doesn't exist, and call #1234:huh() instead. The default implementation of #1:huh just tells the player I don't understand that.

Length 10

create(#1)

The create() function call is used to create a new object. The argument is the parent object; create() then returns a new object which is a child of that object. (Some forks of the LambdaMOO server, such as stunt, also support multiple inheritance. It works more or less as you would expect.) Thus, this command creates a new object which inherits the properties and verbs of #1, described above.

Unlike most object-oriented programming languages, objects in LambdaMoo are not something you create very frequently. This is partly for technical reasons: there is generally a quota which limits the number of objects a player can own, to reduce database bloat. However, it is mostly because objects are very much a physical thing (inasmuch as anything can be physical in a virtual world). If you make an object, players can see it, pick it up and carry it around.

There are patches which you can apply to the LambdaMOO server to get something that resembles a traditional object; these are called "waifs" in LambdaMoo parlance. Waifs have properties and verbs but don't have object numbers, are automatically garbage-collected when they leave scope, and do not appear in the world. If you want to use these you will need to compile the server with the waif patches applied.

If your server has object recycling enabled, the object reference you get is not guaranteed to be unique: it may have been used by a different object in the past. When creating an object this is not an issue, since you have never heard of whatever it was before. However, you need to bear this in mind when using object numbers: #1040 which used to be a vacuum cleaner may have been recycled into a tax form since you last used it. In practice, this is not usually a problem: just as you wouldn't throw out a perfectly good vacuum cleaner, you don't recycle a useful object. (I've found that you usually run into this problem only when you have a reference to something a different player owns, and that player is reaped: all of their objects get recycled.)

\$\endgroup\$
16
\$\begingroup\$

jq

Factoid

jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

Length 0

With an empty code jq just formats the JSON data. Often an essential first step when you need to process a huge .json file:

bash-4.3$ jq '' <<< '{"network":"StackExchange","site":["Programming Puzzles","Code Golf"]}'
{
  "network": "StackExchange",
  "site": [
    "Programming Puzzles",
    "Code Golf"
  ]
}

Length 1

.

The . is the simplest filter, kind of neutral: just the unaltered input (kind of cat). But more important, is the way to refer the current value (kind of $_) in an expression:

bash-4.3$ jq '.*2' <<< '3.14 42 2015'
6.28
84
4030

bash-4.3$ jq -R '{(.+"-"+.):.}' <<< 'foo'
{
  "foo-foo": "foo"
}

Length 2

[]

No, not those [ and ] which delimit an array literal in JavaScript, Ruby, PHP, … (Though that syntax is also valid in jq.) Here [] is more like Ruby's splat operator, which flattens an array:

bash-4.3$ jq '.|"\(.) Mississippi"' <<< '["one","two","three"]'
"[\"one\",\"two\",\"three\"] Mississippi"

bash-4.3$ jq '.[]|"\(.) Mississippi"' <<< '["one","two","three"]'
"one Mississippi"
"two Mississippi"
"three Mississippi"

The difference may be more clear if we use concatenation instead of interpolation:

bash-4.3$ jq '.+" Mississippi"' <<< '["one","two","three"]'
jq: error (at <stdin>:1): array (["one","two...) and string (" Mississippi") cannot be added

bash-4.3$ jq '.[]+" Mississippi"' <<< '["one","two","three"]'
"one Mississippi"
"two Mississippi"
"three Mississippi"

Length 3

add

No, not the plain old addition. That is the same + in jq too. add is a builtin function which adds all elements of an array:

bash-4.3$ jq 'add' <<< '[1,3,5,7,9,11,13,17,19]'
85

To solve Gauss's task of adding numbers between 1 and 100:

bash-4.3$ jq -n '[range(1;101)]|add'
5050

But as it is just repeated +, works for any data type for which + is defined, for example strings, which get concatenated:

bash-4.3$ jq 'add' <<< '["stack","over","flow"]'
"stackoverflow"

Length 4

type

Just tells what type the data has:

bash-4.3$ jq 'type' <<< '3.14 "3.14" [3.14] {"pi":3.14}'
"number"
"string"
"array"
"object"

Of course, in most cases this will be used in some kind of condition when iterating over an array's elements. For example to find out which one is not numeric:

bash-4.3$ jq '.[]|select(type!="number")' <<< '[0,1,2,"cukoo´s egg",4,5]'
"cukoo´s egg"

Length 5

empty

null means nothing, the absence of something.
empty means absolutely nothing, not even nothing.

bash-4.3$ jq '.[]|if.==2then null else. end' <<< '[1,2,3]'
1
null
3

bash-4.3$ jq '.[]|if.==2then empty else. end' <<< '[1,2,3]'
1
3
\$\endgroup\$
16
\$\begingroup\$

Prolog

Factoid

Prolog is one of the first and most popular logic programming language.

Since Prolog is a declarative language based on first-order logic, programs in it can be surprisingly elegant, or devilishly mindbending.

“In Prolog programming (in contrast, perhaps, to life in general) our goal is to fail as quickly as possible.” — The Art of Prolog

Length 1

X

In Prolog, any identifier that starts with an uppercase letter is a variable, which initially has no value. Unlike most programming languages, variables in Prolog can only take a value once (we say that the variable gets unified with something). After unification, a variable cannot be updated (unless backtracking occurs… more on that later). Variables only get a type once they are unified (the type of what they get unified with), therefore a free variable can be unified with anything.

Length 2

X.

This is a valid query in Prolog. Unlike most languages, in prolog you run queries (like in SQL), and the Prolog execution engine will attempt to satisfy that query. In particular, it will unify variables along the way if those unifications make the query true. Each query ends with a period.

Here however, the query is not really meaningful, since we are asking Prolog to check that a free variable X is true, and it is for an infinite number of different unifications (any integer for instance would make this true). Therefore, here is what SWI-Prolog answers to that query:

% ... 1,000,000 ............ 10,000,000 years later
% 
%       >> 42 << (last release gives the question)

Length 3

nl.

In Prolog, any identifier that starts with a lowercase letter is called an atom. They can be used to name predicates, facts, or simply as string-like objects. Here, nl/0 is a predicate which has 0 arguments (hence the /0 notation) and which is a built-in in Prolog. This predicate simply prints a line break to STDOUT:

?- nl.

true.

You can see that Prolog really likes to print true. when it manages to satisfy your query (or false. when it doesn't).

Length 4

X=0.

In Prolog, = is unification. Prolog will satisty this query by unifying X with 0, which is the only possible way of satisfying it.

Length 5

X=[].

In Prolog, the list is a central data structure that you will use constantly. All lists are written in square brackets. A special list that will show up very often (particularly when writing your recursion termination condition) is the empty list, noted [].

Length 6

X=3+B.

Prolog is homoiconic, and as such the above query is perfectly valid. The REPL returns the following:

X = 3+B.

In short, we are unifying variable X with the expression 3+B (which does not get evaluated in any way). If we now unify B with something, this will be reflected in X:

?- X=3+B, B=5.
X = 3+5,
B = 5.

(As you can see, X is not evaluated to 8)

Length 7

X*X#=4

Here I am cheating slightly. To make the above work, you must first run the following query: use_module(library(clpfd)).. This is the constraint logic programming in finite domains (CLPFD) library, which allows us to do very powerful things: for instance, the REPL will return the following for the above query:

X in -2\/2.

\/ represents the union of two domains. Therefore, what Prolog is telling use here is that for X to satisfy X*X = 4 (the # in the query is CLPFD's syntax for constraints), X must be either -2 or 2.

This is a very powerful mechanism that allows to write constraints on variables, without specifying how to find the values that satisfy them. Writing something like a sudoku solver with this library is thus extremely easy: you only have to describe the constraints between cells, and the starting clues. Prolog will then find solutions for you!

Length 8

X=2;X=9.

Prolog is a logic programming language, and as such you expect to be able to use disjunctions. This is exactly what ; (Or) does: X unifies with 2 OR X unifies with 5. When running this in Prolog's REPL, we get the following:

?- X=3;X=9.
X = 3

The REPL halts after printing you this answer, instead of finishing and waiting for a new query. Indeed, Prolog thinks there are other possible answers (and there is one in this case), and so it is waiting to see if you are interested in those. By pressing ;, it will give you another answer:

?- X=3;X=9.
X = 3 ;
X = 9.

which is what we expected to get. Here, Prolog knows there are no other possible answers for what we queried, so it will finish and wait for another query.

The mechanism behind this is called backtracking: when Prolog choses to unify X with 2, it remembers that it made that choice when in fact there are other possibilities (here, unifying X with 9). When we ask for another answer (or if the query had failed after that choice), it will backtrack to the last choice it made and try another one, until no other choice is available.

Length 9

a(ax+b).

Here is a fact, that constitutes your source code. We can make some interesting queries on that fact, to check out Prolog's pattern matching mechanism (remember that identifiers starting with an uppercase letter are free variables):

?- a(X).
X = ax+b.

Cooler:

?- a(X+b).
X = ax.

Even cooler:

?- a(X+Y).
X = ax,
Y = b.

Length 12

length(L,3).

length/2 is a built-in predicate of Prolog which is true if its first argument is a list of length its second argument. Here, we are setting the second argument as a ground integer, and the first as a variable. Thus, we get the following behavior:

?- length(L,3).
L = [_G1500, _G1503, _G1506].

That is, for that query to be true, L must be a list of 3 elements; those elements are _G1500, _G1503 and _G1506 which are variables (those names are internal variable names).

We can also run that predicate with both arguments as variables, and get the following very powerful behavior:

?- length(L,M).
L = [],
M = 0 ;
L = [_G1512],
M = 1 ;
L = [_G1512, _G1515],
M = 2 ;
L = [_G1512, _G1515, _G1518],
M = 3 ;
L = [_G1512, _G1515, _G1518, _G1521],
M = 4 ;
…
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Length 7: That's not cheating. It's explained in the CLP(FD) library documentation that users are encouraged and even expected to have :- use_module(library(clpfd)). in ther initialization file, so that CLP(FD) constraints are avilable in all programs. \$\endgroup\$
    – mat
    May 30, 2016 at 12:28
16
\$\begingroup\$

VB.net

(0 Code Example)

If you import the schema for a XML document, you'll get improved Intelli-sense support for the XML you are using. For example the rss schema.

Dim rss = XMLDocument.Load("path to rss")
Dim items = rss.<

At this point you'll see <channel>

Dim items = rss.<channel>.<

At this point you'll get

<title>
<link>
<description>
<language>
<pubDate>
<lastBuildDate>
<docs>
<generator>
<managingEditor>
<webMaster>
<item>

Let's continue.

Dim items = rss.<channel>.<item>
For Each item In items
  Dim title = item.<

At this point you'll get

<title>
<link>
<description>
<pubDate>
<guid>

Also it also works for xml node attributes. node.@


1 Char

! aka the Dictionary Lookup Literal can be used on dictionary retrieve the value of a key, the key used with the literal can not be a variable and thus changeable at runtime.


2 Chars (VB14 or later)

?. Null Propagation operator

Example usage.

Dim x As String
Dim c = x?.Length

is equivalent to the following code.

Dim x As String
Dim c As Nullable(of Integer)
If x Is Nothing Then
  c = New Nullable(Of Integer)()
Else
  c = New Nullable(of Integer)(x.Length)
End If
\$\endgroup\$
17
  • 3
    \$\begingroup\$ While you don't get an upvote you must first post a single factoid about your language of choice in plain english, no code yet :-) \$\endgroup\$
    – Will Lp
    Jan 19, 2015 at 20:03
  • 2
    \$\begingroup\$ @WillP The rules say the number of characters is upvotes plus downvotes, so (your?) downvote means he can delete the whole post and post a single character thing from the language. That said, the factoid doesn't really have to do with the language anyway, rather with the program most use to write it (Visual Studio). \$\endgroup\$ Jan 19, 2015 at 20:17
  • 2
    \$\begingroup\$ @Namfuak It's upvotes minus downvotes in the way you'd expect. If I said otherwise somewhere then that's a typo. I downvoted this since it does not follow the "no code in the factoid" rule. But it could be fixed or Adam can delete this answer and try again. \$\endgroup\$ Jan 19, 2015 at 20:32
  • \$\begingroup\$ @Calvin'sHobbies Huh, now I reread it and that's pretty obviously what it says. Dunno how I misread it the first two times. \$\endgroup\$ Jan 19, 2015 at 20:37
  • 1
    \$\begingroup\$ Where is continuation? \$\endgroup\$
    – Qwertiy
    Apr 21, 2016 at 10:34
16
\$\begingroup\$

Japt

Japt is a shortened version of JavaScript, created by myself in early November 2015.

Click on any snippet's header to try it in the online interpreter!

Factoid

Japt is heavily based off of JavaScript. After transpiling Japt's syntax features to JS, it is evaluated as vanilla JS. This allows easy building of an online interpreter.

Length 1

Ð

Ah, the letter Eth. (Don't tell anyone, but it's my personal favorite.) This is the first example of one of Japt's defining features: Unicode shortcuts. Each one-byte character from ¡ to Þ has or will be assigned two or more chars to stand in for. Ð happens to stand for new Date(.

Another nifty feature is that missing parentheses are automatically added. This code transpiles to:

new Date()

Finally, implicit output: The last expression (separated by ;) is automatically sent to the output box. On my computer, the output comes up like so:

Sun Nov 29 2015 09:37:30 GMT-0500 (Eastern Standard Time)

One important thing to note is that in the interest of saving bytes, Japt replaces each close-paren with two close-parens, and each space with one. So instead of writing

Ð)+1

you would have to write

Ð +1

Length 2

Now we get to implicit input: N is pre-defined to the evaluated input. U, V, W, X, Y, and Z are set to the first six items. If there are less than six items in the input, the remaining vars are set to 0 instead.

Also, the Unicode shortcut ² is set to p2 . This means that the code is really Up2. All lower­case letters are reserved for methods, and are transpiled to e.g. .a(. This makes the code

U.p(2)

Japt has three main data types: strings, arrays, and numbers. And all three of these have different meanings for .p(). Here's what happens with the different input types:

  • string.p() = .repeat(), so the input is repeated twice and outputted.
  • array.p() = .push(), so 2 is added to the end of the array, and its new length is outputted.
  • number.p() = .pow() (hence the shortcut being ²), so the input is squared and outputted.

Length 3

Uæq

One of Japt's main strengths is its large selection of array manipulation functions. There are many helpful functions that we could use on arrays; more than the 26 lowercase letters can hold. So to get around this limit, we can use the lowercase accented letters in the range à-ÿ. æ returns the first item in the array that returns truthily when run through a function.

Another strength is auto-functions: if a lowercase letter is given in place of a function, it transpiles to e.g. function(c){return c.q()}.

So, this code returns the first item whose .q() returns with a truthy value. But what is truthy? As it turns out, almost everything: the only values in JS that are not truthy are "", 0, NaN, null, and undefined. And q is square root on numbers, which returns NaN for negatives and 0 for 0. So if the input is an array of numbers, this returns the first positive one:

-3   NaN    falsy
 0   0      falsy
-6   NaN    falsy
 7  ~2.646  truthy!
 4   2      truthy
-1   NaN    falsy

This example returns 7. But what about non-numbers? q splits a string into chars, and joins an array, so the only falsy value that's not a number will be the empty array:

[]       ""         falsy
[1,2,3]  "123"      truthy!
""       []         truthy
"abc"    ['a,'b,'c] truthy

The q trick has many other applications, which we will look at later.

Length 4

¡XcV

Let's take a look at functions now. ¡ stands for Um@, and @ stands for XYZ{, which is transpiled to function(X,Y,Z){. So here we have:

U.m(function(X,Y,Z){return X.c(V)})

This results in a whole tree of possible outputs, depending on the types of U and V:

  • If U is a number, m is Math.min and returns NaN.

  • If U is a string, m maps each char X to:

  • If V is not specified or 0, X's char code.

  • Otherwise, NaN.

  • If U is an array, m maps each item X to:

  • If X is a number: X.

  • If X is a string: if V||0 is within the length of X, the char code at V in X; otherwise, NaN.

  • If X is an array: X flattened (i.e. all items in sub-arrays are brought up to the base array).

Length 5

`HÁM!

Believe it or not, this doesn't give the user a ham. ;) On the contrary, it outputs a warm welcome:

Hello!

How does this work, you ask? Well, the secret lies in the backtick: Japt uses the shoco library for string compression. To compress text, you call Oc like so:

Oc"Hello!"

This will give you the compressed string. To decompress, you can do one of two things: 1) Use Od"...", or 2) wrap the text in backticks. This is why Japt is shorter in the "Hello, World!" challenge than almost every other language that doesn't have a built-in for "Hello, World!".

Oh, and one more thing: If you have a quotation mark or backtick (or dollar sign, or curly bracket, or parenthesis, or any combination of the above) at the end of a program, you can leave it off, saving an extra 1 or more bytes.

Length 6

U®¤¬r^

Lots of Unicode shortcuts here: ® stands for m_, and _ stands for Z{Z. ¤ stands for s2 , and ¬ stands for . Putting this all together, we get:

UmZ{Zs2 q r^

If the input is an array of numbers, this maps each item Z to Z.toString(2).split(""). But what is that r^ at the end? array.r() is the reduce function, which takes in a function of at least two parameters, and uses that function to combine each item with the previous value. As an example:

[0,1,2,3,4]rXY{X+Y

This reduces the array with addition. The result is 10; it works like this:

prev value: 0; next value: 1; result: 1
prev value: 1; next value: 2; result: 3
prev value: 3; next value: 3; result: 6
prev value: 6; next value: 4; result: 10.

But ^ is not a function, so what happens? Japt has a nice feature where if the first thing inside parentheses is an operator, it's transpiled to a function which takes in two arguments, and returns the result of the args being combined with that operator. So this whole program ends up as:

U.m(function(Z){return Z.s(2).q().r(function(a,b){return a^b})})

Which maps through each number, turns it to its an array of its binary digits, and finally returns 1 if this contains an odd number of 1s, and 0 otherwise.

Length 7

Uà ®r!-

More array manipulation: à returns all possible combinations of the array. You've already seen that ® is a shortcut for m_, and that r- would reduce by subtraction. But what does r!- mean? The difference is simple: an operator preceded by ! reverses the order of the resulting function's arguments. Here's exactly how this works:

Code  Transpiled
r-    .r(function(a,b){return a-b})
r!-   .r(function(a,b){return b-a})

After putting this all together, we end up with:

U.à().m(function(Z){return Z.r(function(a,b){return b-a})})

This takes all possible combinations of the input array, then reduces each by subtracting the previous result from the current item. For example, [1 3 7] becomes:

Comb.    Reduction       Result
1 3 7    3-1=2, 7-2=5    5
1 3      3-1=2           2
1 7      7-1=6           6
1        1=1             1
3 7      7-3=4           4
3        3=3             3
7        7=7             7

Length 8

Uf¬å+ ä^

Hooray for array manipulation! å is a cumulative reduce (i.e. like r, but returns an array of each intermediate value), and ä maps each adjacent pair of items through the function. As shown before, ¬ becomes , which performs square root on numbers. So if the input is an array of numbers, fq  filters out the non-positive ones, as shown in Snippet 3. Let's try it:

U   [1,2,-3,5,0,7]  [1,0,-1,1,1,0,1,1]
f¬  [1,2,5,7]       [1,1,1,1,1]
å+  [1,3,8,15]      [1,2,3,4,5]
ä^  [2,11,7]        [3,1,7,1]

q has even more potential in this area, which will be demonstrated in a future snippet. This program is obviously not super useful, but hey, messing around with math is fun. :)

Length 9

+² Æn -X²

Here I wanted to showcase one of the features which has the largest impact on the order of inputs: Auto-insertion (specifically of U in this case).

In some situations, attempting to use a method or operator when there is no value immediately to the left of it will cause the transpiler to insert a variable of its own instead of giving an error. In this snippet these three rules are used:

  • At the start of a line, U will be inserted
  • At the start of a function, U will be inserted
  • At the right side of an operator, when the left side is a single variable, the same variable will be inserted

Thus this piece of code is identical to the snippet above after auto-insertions and without shortcuts:

U+Up2  oXYZ{Un -Xp2
^ ^         ^
| |         | Auto-inserted at the beginning of a function
| |
| | Auto-inserted because the left side is just "U"
|
| Auto-inserted at the beginning of a line

What the code does is compute the sum of U and U squared, and then for each value X in the range from 0 to that sum it outputs -U minus X squared. This exact snippet isn't particularly useful, but auto-insertion definitely can save a few bytes especially if you pick the right order of inputs.

Lots to come as I have time to add it!

\$\endgroup\$
3
  • \$\begingroup\$ Are you sure [] is falsy? Seems to be truthy on SpiderMonkey \$\endgroup\$
    – Downgoat
    Dec 7, 2015 at 2:58
  • \$\begingroup\$ @Downgoat You are correct. Apparently I was mistaken. \$\endgroup\$ Dec 7, 2015 at 16:57
  • \$\begingroup\$ Can i has moar snippets? You are at 11. \$\endgroup\$
    – Riker
    Mar 17, 2016 at 0:29
16
\$\begingroup\$

Mathcad

Well, this is not my favourite language, but this definitely hasn't been covered here, and it looks like a great golfing lang to me! To those blissed to not know what it is: Mathcad is sort of like a simplified Matlab, but clunkier. It has existed since 1986, and it is one of the oldest software products of its kind.

Factoid: Mathcad is a purely-procedural programming language with type inference and a really, really weird editor: each operator is added to the program by a keyboard key or combination of keys, but gets displayed on-screen as a (sometimes quite long) keyword.

Oh, and it doesn't support spaces, except in strings. And no tabs or linebreaks. Even if you have a very long line of code. Yes, Mathcad is weird.

Length 1

Here's a simple program in Mathcad:

a

This is a perfectly valid program. It declares a (global) variable a. Mathcad doesn't have any constants. And, since it uses type inference, this variable can become anything Mathcad can make it, from an integer to a matrix. Cool, huh?

Interesting fact: I call it a "variable", but, theoretically, Mathcad does not have any global variables, only redefinable global constants that can be redefined to have a new value, albeit only in global scope.

Another interesting fact: that thing is also a function. I'll explain it later. Just believe me for now.

And yes, this declaration is completely, totally useless. You can even say this causes problems as it limits the key shortcuts we can use if we decide to define it in another statement.

Length 2

Here's another simple valid program in Mathcad:

a' (equivalent to 'a)

Formatted as (a)

What does this do? This takes our newly declared a into parentheses! This doesn't do anything really, but is still valid code, too. Parentheses in Mathcad are normally used in arithmetical expressions.

I hope you're beginning to see the sheer weirdness of Mathcad. An apostrophe as a shortcut for parentheses? Who could have ever guessed it? By the way, we will get the same thing if we just type in (a). But be warned, if you haven't typed in an opening parentheses before a first, no closing one allowed! Why? No idea...

Length 3

Time for some real stuff! We can do (global) variable assignment now! a:1 (equivalent to a=1 in this case) Formatted as a:=1

We've assigned the value 1 to our "global variable", making its type a (signed, no unsigned types in Mathcad) integer. Or, speaking with Mathcad's terms, we "defined the global constant a". As a wasn't defined before, = maps to global variable assignment as well as : (this won't work if a has been already defined or simply declared). Funny thing: the type is limited to the range of... [-999999999999999, 999999999999999]. Although Mathcad "boasts" calculations on numbers with as long as 17 decimal places, in reality, it will work without error with 15-decimal-place integers maximum even with peak settings (at least on my copy of Mathcad 15). Why does it even count them by decimal places? I can only guess...

Length 4

Now, some functions!

b(c) (finally something formatted just as typed)

This is a valid piece of code that is actually a function declaration, something like a C function prototype. It declares a function b with one parameter, c. Note that you can't leave the parameter list between the parentheses empty.

Why? Well, the proper Mathcad syntaxis for a 'void'-parameter function is actually... to omit the parentheses. Yep, exactly the same as declaring a "global variable". In Mathcad, every "global variable" is sort of like a parameterless function that always returns one thing - the value it was initialized to by a definition or a redefinition. I'll demonstrate it later.

Oh yes, and functions can be redefined, just like variables. However, Mathcad has no overloading, so the function called will always be the last one declared. How very, very handy.

Funny thing about our little function declaration: it is just as useless as a "global variable" declaration. It won't allow us to call itself, it won't allow us to use it to call a function with the same signature that will be added later. It will just sit there and be 100% syntactically correct.

Length 5

Let's do something fun with our functions!

c:b{1 (formatted as c := b ← 1)

Note that this definition raises a warning about redefining a built-in Mathcad unit. Yes, Mathcad is one of those languages that sport a standart library built in right into the language, just like PHP. c is internally defined as a "meters-per-second-speed-floating-point" type variable approximating the speed of light.

So what does our definition do? Nothing important, actually. It is a parameterless function that does one thing: define a local variable b, initialize it to 1, and return the result of the expression, which is also 1.

Actually, Mathcad has an explicit return operator, but it not always needed: Mathcad will return the last thing it sees in the function if it doesn't see the return. Period. Be it a value, a variable, or the result of an expression, it will be returned.

Another funny note: local function variables can have default values if a "constant" of the same name has been declared in the global scope. You can change the local variable's value, but you cannot change its global scope counterpart's value. So yeah, in that sense, Mathcad's "global variables" could be called "constants" (although I think that "weird crap" describes them much better than either of these). So, no shared function state. That's sad since Mathcad gives us no multithreading capabilities to compensate for that.

Length 6

Still not enough space for making a multi-expression function, so let's play with some ranges instead! Also, it's a good time to finally reach (numeric) evaluation.

0,2;9= (formatted as 0,2 .. 9 = )

This is a standalone expression that defines a range from 0 to 9 inclusively with a 2 - 0 = 2 step.

The operator basically works like this: range-start {optional: , range-start + range-step} ; range-end

It is then evaluated numerically by the = operator. In Mathcad, "evaluate" = "output". In this case, it outputs a (vertical) table of all the elements of this range, which are, in this case: 0 2 4 6 8. If you remove ,2, the step will default to 1, giving you 0 1 2 3 4 5 6 7 8 9.

Length 7

Ah, finally, "linebreaks" in functions!

a:b{1]2

Formatted as:

This is a function that takes no parameters and returns... 2. This demonstrates two things: Mathcad's idiotic "line breaks" and its weird and almost completely useless "sequence-point subblock" construct.

Yes, my friends, this is what Mathcad gives us instead of line breaks. ] means "add line after last value, symbol, block in parentheses or empty line". So, if you want to write an expression on one line and another expression on the next line, you have to first prepare a line for the second expression, and then write the first expression. Otherwise, the last part of your expression ends up in its own small "sequence-point" sub-block. This can be a terrible pain in the ass.

Why do I call it a "sequence-point subblock"? Because it is basically the same as the old C parentheses-and-commas sequence-point construct: (expr1, expr2, ..., exprn). To those of you who do not know what this is: it evaluates all the comma-separated expressions in order and returns the last one. The subblock above does exactly the same: it evaluates the expressions on each line in order and gives out the result of the last one. Yes, this could theoretically be useful in structuring a function. Probably.

By the way, the "sequence-point subblock" can also be used in global context. Just type in a value/symbol/block in parentheses and hit ], then the next one, etc., and when you're done, hit = to get the last value. This can be useful in... um... oh, I give up, it's also totally useless.

Length 8

And here's how you get an expression per line in Mathcad:

a:]b↑b{1 (from here on, I'll use the arrow symbols in place of the arrow keys).

Formatted as:

This is a parameterless function that assigns 1 to b and then returns it.

I think this needs a little explanation. First, we create our function with a:. Then, we add a new line to it with ]. The cursor automatically travels to the added line, so we type b there, then use the up-arrow key to return to the previous line, and there initialize b to one.

Of course, this is golfed. In Mathcad, it is easier to add as much lines in advance as you might need, then move your cursor to the first one with the mouse and start typing your expressions, hitting the right-arrow key every time you need to go to the next line. *insert facepalm here*

\$\endgroup\$
2
  • 4
    \$\begingroup\$ Mathcad prepared against hidden whitespace programs. \$\endgroup\$
    – randomra
    Jan 25, 2015 at 19:59
  • \$\begingroup\$ Whilst I'm please that you have drawn attention to Mathcad, might I suggest that you become more familiar with Mathcad and edit your remarks accordingly? Mathcad is much more capable, and easier to edit, than you suggest. It does numeric computation using the IEEE 80-bit format (hence the 17 digits) but stores using the 64-bit format. It also has an arbitrary numeric precision symbolic processor. Look up Global Variables - they have a specific meaning in Mathcad. For general use, Mathcad is my go-to maths application as it's a lot simpler to get stuff up and running (I also use Matlab). \$\endgroup\$ Mar 10, 2016 at 11:54
15
\$\begingroup\$

STATA

Factoid: STATA is a statistical language that is used mainly for economics modelling.

Length 1:

l

This lists all variables and every observation for each variable in a big table. It is shorthand for the list command and demonstrates that many commands can be shortened to save characters when golfing.

Length 2:

di

This is short for display, which can take any number of arguments separated by space and displays them to the console. With no arguments, it just prints a new line.

Length 3:

#d;

This is short for #delimit ; which changes the delimiter from a carriage return to a semicolon. In fact, anything but #d cr will change it to a semicolon.

Length 4:

so a

This command sorts the data in memory by variable a in ascending order.

Length 5:

cap "

The capture (shortenable to cap) command captures the errors that occur with other commands, including syntax errors. Here, the non-closed quote is an invalid command in STATA, but because capture is used, there is no error, and code can continue.

Length 6:

drop a

This command removes the variable a (and all values for a for observations in the dataset). In addition, drop can be used to specify a list of variables to drop or even a list of observations (with slightly different syntax).

Length 7:

l ///
a

Like in many languages, STATA allows comments with //. However, adding an extra / will cause the command to continue onto the next line, so here, this is equivalent to l a, which will list each observation's value for the variable a.

\$\endgroup\$
1
  • \$\begingroup\$ Epidemiologists and survey statisticians also seem to love Stata. I haven't had much exposure to it so I'm excited to see where you go with this. \$\endgroup\$
    – Alex A.
    Jan 20, 2015 at 22:05
15
\$\begingroup\$

MUMPS

Factiod

MUMPS, or M or Cache, was a programming language created at the Massachusetts General Hospital. In fact, that's where the name come from. No, it doesn't come from an infectious disease. The name is an acronym--Massachusetts General Hospital Utility Multi-Programming System.

One interesting piece about MUMPS is that there is no restriction on language specific keywords. Couple this with the fact that whitespace is somewhat important and you can easily make some big goofs in code.

1 Character

Q

In MUMPS, it is possible to shorten most keywords down to a single letter. For instance, the Q command is short for quit and will terminate the program.

2 Characters

$H

$H will help you get the current time. This command returns the number of days since 31-DEC-1840 followed by a comma, followed by the number of seconds since midnight. So, calling $H at 5pm on 13-MAR-2015 would return 633624,61200

3 Characters

N Q

Now, this will be interesting. At first glance, you would recognize the Q command from before. However, this is where MUMPS can break, easily. The N command is short for new and is used to initialize variables. Since all data in MUMPS is technically strings, no data types are needed. However, there are no reserved keywords, so we now have a variable called Q.

4 Characters

W @Q

Now life is getting even more interesting. Let's set up the environment a little. First, you need to know that W is short for write. Think print and you're good. So, we have some variables defined as below:

N Q,A
S Q="A"
S A="B"

Now, if we take the line above in our example, what do we write out? At first thought, maybe the answer is A. That would be wrong. The answer is B. That's because the @ symbol is used for indirection, which allows you to reference variables by the name stored in a different variable. This is similar to reflection.

5 Characters

2+3*9

Now, in any normal programming language, the expression above would evaluate to 29. However, MUMPS is strictly left-to-right. This means that the expression above would evaluate to 45. Liberal use of parentheses is recommended.

\$\endgroup\$
2
  • \$\begingroup\$ Why does $H return the number of days from Dec 31, 1840? Is there something special about that date? \$\endgroup\$ Sep 8, 2015 at 17:25
  • 3
    \$\begingroup\$ @ASCIIThenANSI Legend has it that when Mass General was in the process of creating MUMPS, they wanted to be sure that their date system would encompass all the dates they might ever need to enter. In surveying their medical records (on paper at the time), they found that the oldest date they had on file was the birthdate of a (since-deceased) patient who was born in 1841. And so, it was decided that the MUMPS epoch would start on Jan 1, 1841. \$\endgroup\$
    – senshin
    Sep 24, 2015 at 23:26
15
\$\begingroup\$

gs2

Factoid

gs2 is my own little golf language that has the highest average score across submissions of all languages on shinh's golf site. It uses all 256 bytes, so it's like a cross between CJam and machine code. It's not perfect, but sometimes it's really, really good.

Note: I'll encode all of the programs in CP437, as if they were printed on a DOS computer, because I don't know of any better character set that assigns a symbol to all 255 bytes. (Even this one lacks a glyph for FF. Oh well.) To the right of each snippet, you'll find a hex dump.

Length 1

f                          66

I wanted to one-up goruby's 1-byte Hello, world!, so... This prints "1\n2\nFizz\n4\nBuzz\n...". :)

Length 2

ï≡                         8B F0

8B is Python's islower() function, but it also works on bytes. __ F0 is a 1-byte-block filter (it goes all the way up to __ __ __ __ __ __ F5). Thus, this program extracts all of the lowercase characters from STDIN.

Length 3

0▓B                        30 B2 42

If the first byte of a program is 30, it's in line mode -- sort of like Perl/Ruby's flags. The remainder of the program, B2 42, will get mapped over each line of input.

B2 is called counter, and the first time you push it, it's 1, the second time it's 2, etc. There's no way to reset it or anything. Dead simple.

42 is swap, which will put the counter before the lines we're looping over. Thus this will perform a very lazy kind of line numbering:

abc          1abc
defgh   ->   2defgh
gs2!         3gs2!
\$\endgroup\$
15
\$\begingroup\$

Motorola MC14500B Machine Code


Factoid

Patented in 1977 by Motorola, Inc., the Motorola MC14500B is a CMOS processor in a 16-pin package. It has a 2-way data conductor (pin 3), and has 16 four-bit opcodes.


Length 1

Hexadecimal:

1

Binary:

0001

Explanation

1    Load data from the I/O pin to the register

With this 4-bit opcode, the register's value becomes the input value received by the I/O pin.


Length 2

Hexadecimal:

18

Binary:

0001 1000

Explanation

1    Load data from the I/O pin to the register
8    Output the register's value to the I/O pin

This single-byte operation, takes an input value via the I/O pin, and outputs via the same pin. Essentially, it is a cat program.


Length 3

Hexadecimal:

18F

Binary:

0001 1000 1111

Explanation

1    Load data from the I/O pin to the register
8    Output the register's value to the I/O pin
F    Jump back to the first opcode of the program

This will loop, taking an input and outputting its value. I used this snippet to demonstrate an infinite loop.


Length 4

Hexadecimal:

178F

Binary:

0001 0111 1000 1100

Explanation

1    Load data from the I/O pin to the register
7    If the register value is equal to the I/O pin's value, set the register to 1
8    Output the register's value to the I/O pin
F    Jump back to the first opcode of the program

This snippet will take an input, and output it's complement. This will continue in an infinite loop.


Length 5

Hexadecimal:

578EF

Binary:

0101 0111 1000 1110 1111

Explanation

5    Logical OR on the register and I/O pin
7    If the register value is equal to the I/O value, set the register to 1
8    Output the register's value to the I/O pin
E    Skip the next opcode if the register's value is 0
F    Jump back to the first opcode of the program

This snippet will take an input (essentially "Do you want me to stop looping?"). If the input is a 0, it will loop infinitely, but if the input is a 1, it will not loop.

If the input is 1, it will output 0 (for "not looping") and terminate, but if the input is 0, it will infinitely output 1.

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

Element

This is a language that I invented in early 2012 to be a simple golfing language. By this, I mean that there is very little to no operator overloading. The operators are also simpler and fewer in number (all single characters) than most modern golfing languages.

You can find the current version of the Element interpreter, written in Perl, right here.

The most interesting features of this language are its data structures. There are two stacks and a hash that are used to store information. One stack is used mainly for arithmetic, while the other is used mainly for logic. The hash is used to store "variables." The use of a hash means that the number of variables can be practically unbounded.


Length 1 Snippet

#

The # operator removes and destroys a single item from the top of the main stack (the m-stack or arithmetic stack). When standing alone, this doesn't do anything at all.


Length 2 Snippet

_`

This is a "cat" program, or a program that outputs its input. The _ operator gets a line from STDIN and puts it on the main stack. The ` operator (a backtick) removes the top item from the main stack and prints it to STDOUT.


Length 3 Snippet

!{}

This program is an infinite loop. The ! is a logical NOT. The control stack starts empty, logically equivalent to "false," so we must invert it and put a 1 on it. The {} form a while loop. It repeats as long as the top value of the control stack is true (non-zero and non-empty-string). Since the control stack will always have a 1 on top, this repeats forever.


Length 4 Snippet

_2^`

This is a program that squares the input and prints the result. The ^ is a operator which performs exponentiation. Since this is stack-based, the 2 must be pushed on the stack before the ^ is performed. The ^ is just one of the many basic arithmetic operations possible, such as addition or modulo. All arithmetic takes place on the main stack.


Length 5 Snippet

_'[_]

This code reads a line with a number as input and then reads that number of additional lines. This can useful in some golf challenges.

The square brackets form a FOR block, which also doubles to serve as the language's IF block. FOR blocks look at the top value on the control stack and repeat the code inside that number of times. The first line of input is transferred to the control stack with '. Element can be rather heavy with the apostrophes/quotation marks/backticks sometimes.


Length 7 Snippet

_,1+,#`

This takes a character from input and outputs the character with the character code 1 greater than that. It's like a ROT1 cipher without the rotation. The , is the char<->code operator, which pushes both the number and code value for its input. The first occurrence is used to convert to a number, of the second output is used. IN the second occurrence, the number is discarded with # and the character is outputed.


Length 12 Snippet

1_'[3:~2@+]`

This prints the Nth Fibonacci number. New commands here are :, ~, and @. The : operator creates copies of the top item on the main stack. It's top argument, the 3 in this example, determines the number of copies. So, 0: is the same as #, 1: is a co=op, 2: makes one additional copy for a total of 2, etc.

The ~ is variable reading. Given a string (which can also be a number) as an argument, it returns the value that was previously stored in that variable. In this example, we are reading from a variable (the number we just made copies of) that we never stored anything in. This gives the empty string, which serves as one argument for the next operator. If we simply replaced ~ with 0, then we would have to insert a space between the 0 and the 2.

The @ is stack manipulation. Element only has one operator for rearranging the order of stuff within the stack (as opposed to moving things between stacks, which are ' and "). The first (bottom) argument of @ is the source index, and the second argument is the destination index. In this program, the arguments are 0 (represented by the empty string) and 2, so this operator consumes those numbers, and then moves the 1st thing in the stack to be the 3rd thing in the stack.

1                  push a 1
 _'                take input then move it to the control stack
   [      ]        FOR loop
   [3:    ]        make two additional copies of the top number (3 is the total count)
   [  ~   ]        turn one copy into a zero
   [   2@ ]        move from position 0 to position 2, behind the old number
   [     +]        add the old and newer number
           `       output the result 
\$\endgroup\$
1
  • \$\begingroup\$ Update please.. \$\endgroup\$
    – Riker
    Mar 31, 2016 at 15:34
15
\$\begingroup\$

Jolf

0-vote

Factoid: Jolf is my personal utility language, and is sometimes suited for golfing; it was created mainly out of frustration trying to learn Pyth.

1-vote

τ

Jolf is encoded in ISO-8859-7, the Greek encoding. Not only is this one character, but it is also one byte. This stands for 2*pi, or the literal constant tau. Try it here!

2-vote

~ (there is a trailing space)

The tilde is one of the many extender functions in Jolf that allow for 2-byte sequences of characters. In this case, ~ is the ISO-8859-7 encoding. Try it here!

3-vote

ͺπt

This simply reads "pair pi and ten"; ͺ being the function that wraps two elements in an array, π being pi, and t being ten. (Also, Jolf has implicit output and that's good for stuff.) Try it here!

4-vote

Ξhi!

Jolf is hostile. It does not like being talked to. Therefore, it says "ATTACKING " when prompted. Just kidding, this is actually Jolf's string compression in action. In this case. it's using it's dictionary. Try it here!

5-vote

»HΒM!

This is Jolf's string compression in action. This output's the string "Hello!". Jolf uses shoco for compression/decompression. Try it here!

6-vote

ΣdQH1j

This is the first complex program here! Σ is function summation that accepts a function, a minimum, and a maximum. In this case, the function is dQH. d begins a single-arity function with arguments H, S, and n. H is the only argument we are concerned with for the moment. In this case, it is the number being acted upon. QH squares H, and j is the input. So, from 1 to the input, we count the sum of the squares. (If we were golfing, we could move the square function into a lambda as this: ΣλQ1j.) Try it here!

7-vote

mΦx0/9t

This is another one of Jolf's builtins: Fibonacci with custom seeds. In this case, we take input (x) and perform the Fibonacci sequence with Φ(0) = 0 and Φ(1) = 9/10, and that Φ(n+2) = Φ(n+1) + Φ(n). Try it here!, or see the first 16 results in the sequence.

8-vote

₯S₯C+'0q

This is a sort of "growing" quine. is the document package, and this is what it looks like explained:

₯S₯C+'0q
₯S        set the value of
  ₯C      the code
    +'0   to "0" +
       q  the source code

Try it here!

9-vote

U+ΏQm4HXΏ

This is the distance formula for two array inputs! Ώ defines a function Ώ which can later be used.

U+ΏQm4HXΏ
   Qm4H    square the asum of H (e.g. if H = [a,b] m4H = a-b)
  Ώ        a function Ώ does this
       X   initially called with eval'd input
 +      Ώ  added to Ώ(x) (implicit input)
U          square root

10-vote

ΜzάdySHHHH

Try this one here!

I'm calling this the "be quiet, jrich!" program. It outputs this, using Jolf's turtle:

jrich is quiet

This looks a lot like jrich's avatar. This is how it works:

ΜzάdySHHHH
Μzάd        map 1 .. 16 over this function
    yS      create a square
      HH    at (H, H)  ; the index
        HH  of dimensions H x H

11-vote

"Hello, %!"

This greats the user, using string interpolation (%) and implicit input.

Try it here!

12-vote

ps"afaik:lol

This outputs as far as i know:laughing out loud. Apparently, Jolf likes to text. Oh well.

13-vote

~jd=ΏmΓChHHΏS

This takes input (implicitly). It finds all pairs of integers below the input x that satisfy the condition of being before a number having the same collatz sequence length. Explanation:

~jd=ΏmΓChHHΏS
~jd            all pairs satisfying condition (think "~jenerate")
    ΏmΓChH     define a function Ώ that heads H and finds its collatz sequence length
          H    call Ώ on H (outer H)
   =       ΏS  call Ώ on S and see if its = to (^)

This is a demonstration of the concept, rather than a helpful one. Here's one that gives more clear results and filters self equal arrays:

ψh~jd=ΏmΓChHHΏSxd~!=FHgH

Can be golfed, but eh.

\$\endgroup\$
15
\$\begingroup\$

Cheddar


Cheddar is a high-level, functional + object-oriented programming language designed to make programming easier, faster, and more intuitive.


Due to the fact Cheddar is still in development, running Cheddar programs can be rather difficult. Ping me in chat, @Downgoat, and I'll help you test this stuff out.


Factoid

Despite Cheddar's tasty name, it is not edible, if you'd like to eat Cheddar, please go to your local grocery store, not the Github.


Length 1 Snippet

1

This is a number. You probably guessed that but Cheddar's numbers also have some cool features:

0b1011  // Binary number
0o1337  // Octal number
0xFFFF  // Hexadecimal number

123_456_789 // One hundred twenty three million, four hundred thousand...
1.333333333 // Decimal number (yes this is a regular old floating point)

Length 2 Snippet

[]
""
''

These all create iterables. The first is an array []. The second and third are strings. In Cheddar strings may have literal newlines in them.

Length 3 snippet

|>9

This creates a range from 0 - 9, it is represented as an array so you can iterate over it, reverse it. Do anything you want!

Additionally you can use binary |> to generate a range from [a, b]

 0|>4

the above generates: [0, 1, 2, 3, 4]

Length 4 Snippet

true

This creates a boolean with a value of true. This isn't very interesting, unfortunately.

Length 5 Snippet

1?2:3

This is the ternary operator. This is the same as the following:

if (1) { 2 } else { 3 }

The difference is the ternary is an expression so rather than doing:

var a: String
if (goat.type == saanen) {
    a = "bleeeeeet"
} else {
    a = "baaaaaa";
}

You can do:

var a: String = goat.type == saanen ? "bleeeeeet" : "baaaaaa"

Length 6 Snippet

(a)->a

This, obfuscated looking code is actually very simple. It defines a lambda, or anonymous function taking one argument, a, and returns it. Note the parenthesis are optional, the following is just as valid:

a->a

Now, if you were to call foo, it would return the value passed:

print foo(123) // prints `123`

Length 7 Snippet

var a=1

This is the shortest assignment in Cheddar.

Additionally other ways of declaring variables

const foo = bar        // constant
const foo: String = bar // Same but requires `bar` to be a specific type
var foo = bar       // Can be changed, so can the type
var foo: String = bar // Can be changed but only to another string

Length 9 Snippet

String::9

This shows a cool feature of Cheddar's called casting. Classes each have defined behavior for when any class (in this case Number), is cast to them. This would output "9";

In this example String's Number cast is called which in turn casts to a string. You an also swap this around to do a number cast:

Number::"9"

which would output a number 9.

In the event a cast fails, Cheddar throws an error. I'm planning on adding an operator castable which checks if a certain value (LHS) can be cast into (RHS). Which would work like:

if foo castable Number
    print Number::foo
\$\endgroup\$
0
15
\$\begingroup\$

Microscript

Microscript is a new expiremental golfing language I've been working on recently. For my Death By Shock Probe challenge, I was able to write a program that would have beaten out the leading Pyth entry by one byte, except for the fact that the language is too new to be eligible to actually compete in that challenge.

It uses a pair of stacks to manipulate data, and currently has just over 30 distinct commands

The esolangs wiki article can be found here

Length 0 snippet:

The empty program prints 0, followed by a newline. This is because the main register is initially 0, and printing is implicit unless otherwise specified.

Length 1 snippet: p

Prints the contents of the register to the output, followed by a newline. On end of execution, this will be done automatically, unless execution was halted by the h command.

Length 2 snippet: 99

Any positive integer literal not part of another command will increment the main register by that value. Thus, unless part of another command, this will add 99 to the value in said register.

Length 3 snippet: is*

Currently the shortest example program on the esolangs wiki article. Takes in an input and squares it. i takes a number from the input and writes it to the register, s pushes it to the stack (unlike in HSPAL, this does not zero the register), and * pops it off the stack again and multiplies it by the value in the register, writing the result to the register. Then, as mentioned above, the new value is printed implicitly.

Length 4 snippet: isi+

Another example program from the esolangs wiki article. Takes two inputs and outputs their sum.

Length 5 snippet: '~Pph

'<any character> is the language's equivalent of a character literal. P prints as a character while p prints as an integer. Finally, h halts immediately without the implicit printing. Therefore, the output from this is ~126. This is technically equivalent to the shorter (3 byte) '~P.

Length 6 Snippet: i{z1p}

This is a truth machine which converts values not in {0,1} to 1. The closing bracket is optional in this case, but I already had a length 5 snippet. {} is the equivelent of BrainF***'s []; Microscript uses square brackets for other purposes.

Length 7 Snippet: 20ec1r4

Simulates the rolling of 1,048,576 four-sided dice. This is what would have been the winning entry for my afformentioned Death By Shock Probe challenge had Microscript come out a short time earlier. The c command was the language's first form of iteration- essentially "zero the register, then repeat the following a number of times equalling the value that was in the register before it was zeroed". 1 increments by 1, and r4 increments by a random integer on [0,4). Lastly, e is a base-2 exponential function while E is the base-10 equivalent. Thus, 10Ec1r4 (or, equivalently, 1EEc1r4) would simulate the rolling of ten billion four-sided dice. Eventually.

Length 9 snippet: 1{I[h]fan

A cat program that terminates on the first empty line (as the language currently lacks EOF detection)

Length 11 snippet: 0"Caxq"Caxq

A reverse quine, and it's even one byte shorter than the one in the esolang article

Length 13 snippet: ic1s]z1{[ph]*

Calculates the factorial of a number given as input. Limited by the language's 64-bit integer type.

\$\endgroup\$
15
\$\begingroup\$

Hexagony

Images created with Timwi's tools with link provided in the Factoid! The headers Length n Snippet are Try It Online! links :)

Length 5 Snippet - One of the Logic Gates

?<!@<

This is the AND gate, from one of the 16 Logic Gates answer by Martin Ender♦. In his answer, the explanation was left for readers as practise. Well, maybe it's time for the solution:

and1

First ? reads the first input.

If it is 0, then the IP got reflected to NE direction at < and directly wraps "to the left" (as it is <=0) and got printed at !. Whatever it reads at ?, it wraps and stops at @.

and2

If it is 1, the IP takes the right branch for the "conditional" and hit the "inclined mirror" side of < and got reflected back and hit the "hub" side of < which sends it to W direction to read another input. It then wraps and hit the "horizontal mirror" side of < and gets itself to an implicit-if at the corner. 6 instructions made within this blue path.

The different usages of < are all demostrated in this example.

If the second input is 0, then the IP goes along the red path above, which prints a 0 and reads the "third" input and stops.

If it is a 1 instead, yay we finally got 2 1s for the AND gate! The IP goes along the green path and prints out the 1 and terminates!

Length 3 and Length 4 Snippets - Cats

These 2 are simplified (thus not a very good version) of a cat program. For a real working one, please see here.

,;~

This reads and prints and also outputs a lot of trailing mysterious symbols. What's happening?

, reads a byte and ; prints it no matter what , gets (If there is no input, , will return a -1 and ; will print it modulo 256 which is 255).

Here is a trick which is useful in creating Hexagons: Using ~ (negation) to control the direction the IP goes before it reaches an if (no matter it is an implicit one or an explicit one like < and > and some other conditionals).

If you find this hard to understand, then it's worth mentioning that this is not a linear loop. As an exercise imagine the above are put into a 2-hexagon and you'll see why we need ~ to do make a loop with the implicit if :P The code basically runs in the same manner as in the length 2 snippet below!

Thus, when there is a byte, the memory will be positive and ~ makes it negative so it goes back to the top to read another byte. Yet it won't stop...

So let's see the length 4 version of the cat.

<,@;

When you try this, it looks good. Finally we have one program which stops!

cat4

It starts on the top left with an initial value of 0. A trick here which is (again) quite common - deflect the initial IP with <. This is particularly useful when the main loop should end when the calculated value is <=0.

Here it comes to the blue path. ; prints the null byte (as it is initially 0) and , reads a byte. An implicit-if decides if it should go to the green one (doing nothing and wraps back to the main blue loop for printing this byte) or it should go to the red terminal @.

In some code golf challenges, it is acceptable to have null bytes printed before the desired output. However this is not the case for the simple cat challenge attached above :P Also, this does not handle null bytes \0 well. If you are curious how to do the cat with 6 bytes which handles \0 and prints nothing else and stops, check it out! (The 6 bytes solution is shown after the 7 bytes)

Length 2 Snippet

This won't end. Print all non-negative integers separated by -.

!(

Not really. Indeed this is printing the unintialized edge as number (0), then decrement it and print again without a separator (-1, -2, ...)

This is an illustration of both the Implicit Loop (wrapping) and Implicit If.

The IP starts at !, goes to the right to ( and wraps to... not (directly to) ! but somewhere else first. Because the code is used to fill in the smallest possible hexagon that can hold it:

showcase_2

(Blue) For the existing code, after IP runs ( (decrements) and the memory edge becomes -1, it wraps to the middle row and goes all its way to the corner.

And, as its value is <=0, it goes to the left, which is the top row and we hit ! again which prints -1 and so on...

(Red) And if you change the source code to !), it won't print 01234.... Because when it hits the corner, the memory edge is >0 and it turns to the right option (Pun not intended) which is the lower edge, and the lower edge wraps back to the middle - however all the ops are no-ops so the IP can never escape from the loop.

Length 1 Snippet

:

If you try it, it ends soon and nothing will happen. Well 1 byte snippet in Hexagony can't do much.

: is the division in Hexagony and the result is rounded towards -infty.

Why introduce this? Lemme introduce the Memory Model of this one. Without loss of generality (it sounds good using Maths phrases), this is the initial Memory Pointer:

memory_model

Like Instruction Pointers which has an Op which it's currently on (a position) and a direction, the MP also has an edge (which holds a value) and a direction.

The edge on its left is its Left Neighbor (L) and that on right is the Right Neighbor (R).

Like +, -, *, and % (Modulo), : is also calculating L (operation) R.

One "interesting" thing about : and % is that when the Right Neighbor is 0 (the default value of an uninitialized edge), it silently errors out and hence terminating the program. This behaviour sometimes saves bytes when the termination @ is not used to stop the program.


I have read the answer here which is nice :P I also found some interesting snippets on this site thus I would like to try to get a chance to post them. I love Hexagons!

Factoid

Hexagony, as its name suggests, gives programmers a painful experience (agony) playing with Hexagons, with its Instruction Pointers (IP) and Memory Pointers (MP). Great thanks to Timwi who created Esoteric IDE for debugging Esoteric Languages and Hexagony Colorer which helps explaining the coupled IP paths.

When an IP goes out of the Hexagon, it wraps (Yup, implicitly looping) as if the Hexagon is used for tiling the ground. (Not exactly the case, because if you really wanna connect all wrapping paths, you would end up their edge overlapped like the graph on the right) Wrapping c1234 wraps to 567890 wraps back to c1234... abcd wraps to efgh and goes on... and we hit a corner.

For corner cases, there will be an Implicit-If, with <=0 is left and >0 is right. Say you (the instruction pointer when you are programming) go all the way efgh.3. to the corner. You are facing East. You would either wrap to the top which is on your left and the bottom which is on your right. If the MP is pointing to a memory edge which is <=0 you goes to the top, otherwise you goes to the bottom.

True beauty lies in making use of the implicit features and fitting different parts of the algorithm into Great Hexagonal Unity, with the use of mirrors (always like playing with scientific puzzle solving game).

\$\endgroup\$
1
  • \$\begingroup\$ Very nice diagram to explain the wrapping behaviour! :) \$\endgroup\$ Oct 28, 2016 at 19:48
15
\$\begingroup\$

Maple

Length 15

type(1,posint);

Type checking is an important aspect of input handling for procedures and commands.

> type(1,posint);
  true

Length 14

plot3d(cos(x))

3D plots are very useful for visualizing mathematical surfaces. enter image description here

Length 13

Matrix(10,10)

or

<<1,2>|<3,4>>

Matrices are one of Maple's fundamental data structures. It is possible to perform many common operations, including numerous operations in Linear Algebra on matrices. There are several calling sequences for making a new Matrix. Above are two of the most common: The Matrix command generates a new Matrix with r rows and c columns:

Matrix(r,c);

The shorthand notation < > can also be used to input a matrix.

<<1,2>|<3,4>>;

2x2 Matrix

Length 12

f:=x->2*x+12

A function can represent a function call, or application of a function or procedure to arguments. In the example above, a new function called 'f' is created that takes an argument 'x', and returns 2 times the argument plus 12.

> f:=x->2*x+12;
> f(4);
  20

Length 11

assume(x>0)

The assume routine sets variable properties and makes it possible to set relationships between variables. A common use is shown in the example above: the assume routine declares that a variable 'x' is a positive real constant. Applying such an assumption makes it possible for Maple to simplify expressions such as:

simplify( sqrt( x^2 ) )

Which returns 'x' only after an assumption is placed on the variable 'x'.

Length 10

D[1](f)(x)

The D command serves different purposes. It is primarily a differentiation command, similar to one of Maple's most used commands, diff, but it is also more general in two ways: it can represent derivatives evaluated at a point and can differentiate procedures.

Length 9

exp(I*Pi)

Euler's identity states that exp(I*Pi) + 1 = 0. In Maple's 1-D code, this is 9 characters long, however using 2-D Math notation, this can be displayed using 3 characters (4 if you count the space needed for the implicit multiplication of I and Pi):Euler 2-D Math

Length 8

plot(Ci)

This is the first entry that uses one of the most important parts of Maple: plotting. Even though it is possible to construct a plot with less characters, i.e. plot(), this example gives a much more interesting result: the plot of the Cosine Integral.

Cosine Integral

This certainly isn't the last time you'll see a plot in this list as there are many more interesting expressions and plot variants in Maple. Some other interesting 8-character plots include: Sine Integral:

plot(Si)

Exponential Integral:

plot(Ei)

Natural Logarithm:

plot(ln)

Length 7

cos(Pi)

When evaluating symbolic expressions, Maple returns results in an exact symbolic form. This means that the results are not approximated to any number of digits, rather the result is the exact value for the result. This is also what is known as having results with "infinite precision"!

> cos(Pi);
  -1
> evalf[5]( cos(Pi) );
  -1.
> cos(Pi/4);
  sqrt(2)/2
> evalf[5]( cos(Pi/4) );
  .70710

Length 6

rand()

The rand command returns a random integer sampled uniformly from the range 0 to 10^12−1. Maple can also sample from numerous other statistical distributions.

> rand();
  395718860534

Length 5

1.*Pi
1.0*π

Maple supports arbitrary precision arithmetic. For example, here's Pi to 314 digits:

> evalf[314](Pi);
  3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063

Length 4

999!

Maple can work with very large integers. The Factorial operator computes factorials for given values. The number of digits of 999! is:

> length(999!);
  2565

Length 3

x$5

The $ operator can be used to create a sequence for a given expression. For example,

> x$5
  x, x, x, x, x
> i^2$(i=1..3)
  1, 4, 9

Length 2

x:

Using the colon operator suppresses output for entered commands.

Length 1

Maple is a symbolic computation engine, so you can use the infinity character in computations for integrals, limits, etc. Also, results from symbolic computations can be considered to have "infinite" precision since Maple doesn't approximate purely symbolic results (see Length 7 example).

Factoid:

Maple is a mathematical programming language and computation environment. However, the name “Maple” is not an acronym for Mathematical Programming Language, it’s a reference to its Canadian heritage.

\$\endgroup\$
15
\$\begingroup\$

PowerShell

Length 15 Snippet

(1,0,'E')[$x%2]

It is a very short way to output truthy/falsey values if you are asked to determine if $x is even. (or E for error)

It golfs down a switch statement

switch($x%2){0{1}1{0}2{'E'}}

It can index the array using modulo. So the basic algorithm is:

  • If $x is even, then $x%2 is 0, so first element in array is 1
  • If $x is odd, then $x%2 is 1, so first element in array is 0
  • Otherwise if $x%2 errors, it shows E

Same trick can be applied to output 1 (Truthy value) for odd number.


Length 14 Snippet

$a|% t*y|%{$_}

This combines several snippets below into a very powerful feature. Still using % as an alias for foreach-object, we use both of its position-0 positional parameters: -memberName which takes a string and will return the specified member for each object and can take wildcards provided they resolve to a non-ambiguous name (String's toCharArray in this example); and -process which applies a script-block to each object ({$_} in the example).

The example above is a way to iterate through each character in a string and implicitly output it.


Length 13 Snippet

1,1|select -u

Parameters in PowerShell can both be positional and expanded. Positional meaning if the parameter flag isn't explicitly specified, it can be inferred. For example, Get-Random 10 is the same as Get-Random -Maximum 10, because the -Maximum parameter is positional.

Here, we're using the expandable property of parameters. Since -Unique is the only parameter to Select-Object that starts with -u, we don't need to spell out the entirety of the parameter. Both of these features saves tons of bytes.

The output of this snippet, which feeds an [int]-array into the Select-Object cmdlet is 1, as an [int].


Length 12 Snippet

0xff*2KB-2e6

PowerShell has some weird special operators that allow large numbers to be written in small number of characters.

The 0x unary operator converts characters from hexadecimal to decimal. For example, 0xff --> 255 or 0xbeef --> 48879.

The KB (and MB, GB, TB, and 'PB') unary operators take input on the left and multiply it by 1024, 1048576, 1073741824, 1099511627776, or 1125899906842624, respectively. For example, instead of [int]::MaxValue, or 2147483647, you can write 2GB-1.

The e (exponentiation) binary operator basically takes the input on the left and tacks on (the input on the right) number of zeros. For example, 2e6 --> 2000000.

The output of this snippet as written is -1477760.


Length 11 Snippet

$a=($b=1)+1

In PowerShell, it's very important to remember that you're dealing with objects on a pipeline. This can be manipulated in several ways, and the above shows the concept of encapsulation. Commands placed in parentheses are executed first (as you'd expect), but the output of the command is left on the pipeline to be picked up later. Here, we're assigning $b to be 1, and then assigning $a to be $b+1. This snippet is equivalent to $b=1;$a=$b+1, and shows an easy way to golf bytes anytime you're doing an assignment.

The implications here go beyond just that, however, since it's the PowerShell pipeline and so we're dealing with objects. This means that complex object creations can have nested function or procedure calls, for example calling a constructor and immediately calling a method on the resultant object, and then immediately calling a property on the result. Something like (((New-Object foo).bar()).GetBaz()).baz is perfectly legitimate. In some cases, you don't even need to assign the object to a variable.

Additionally, since anything left on the pipeline is implicitly printed after execution, this means you can accumulate data on the pipeline and print for essentially free. For an easy example, a simple accumulator from 1 to 10 (prints 1, then 3, then 6 ...) can be 1..10|%{($a+=$_)} vs 1..10|%{$a+=$_;$a}, saving a byte, but can save significantly more in other situations. Since we're talking about output, this is a good time to bring up that nearly every output to the console/shell in PowerShell includes a newline (technically \r\n because it's Windows), so if the challenge requires separators we get that for free, too.


Length 10 Snippet

$a,$b=1..9

PowerShell has the capability to do multiple assignment. In the above snippet, $a will be 1, an int, while $b will be (2,3,4,5,6,7,8,9), an int-array. This has the ability to save lots of bytes if you're looking for particular items -- for example, $a,$b=-split$somestring will split $somestring on whitespace, store the first word in $a and the rest in $b. Very useful if you're looping through a string, for example, or re-manipulating the rest of the string in some fashion.


Length 9 Snippet

(4,9)[$a]

PowerShell has very loose type casting. Very loose. We can thus abuse this typecasting to transform array-indexing (as the above) into an if/else statement. For this snippet, if $a will somehow evaluate to a truthy value (a non-zero number, a non-empty string, any other non-$null variable, etc.), the Boolean result will be typecast to a 1 and so the 9 will be selected. Conversely, if $a evaluates falsey, the 4 will be selected. This is PowerShell's x?y:z style ternary if, and is significantly shorter than the equivalent if($a){9}else{4}. It's rare for an actual if/else statement to show up in PowerShell golfing.


Length 8 Snippet

$c+=++$i

A simple example showing a couple basic operations. PowerShell has both pre- and post- increment and decrement operators (++ and --), and they function pretty much like you'd expect, except when it comes to uninitialized variables. Running the above snippet in a brand-new shell will result in ++$i evaluating first as $null + 1 = 1 and storing in $i, then adding that result to $c (also $null), which makes $c equal to 1 as well. Flip the pre-increment to be a post-increment and you get a different result, with $c = 0 and $i = 1, but with $c cast as an Int32. This null-arithmetic is a sneaky way of shaving a couple bytes here or there, especially when it comes to not needing to check if a variable already is initialized.


Length 7 Snippet

,'a'*$b

Yeah, so that's a thing. No, really. It's the PowerShell comma operator and it's used to create arrays. As an inline (binary) operator, it creates multi-element arrays, as in $myArray = 1,2,3. As a unary operator, it creates an array with one member, as in $myArray = ,1. In both instances $myArray.GetType() will tell us that it's a System.Array object. Here, we're coupling this with operator overloading (multiplication, specifically) to create an array of length $b with each element equal to 'a' -- that is, we can create and pre-populate an array in one go. It's important to note that the array element is evaluated once and then multiplied, so you can't do something fancy like $a=1;$b=5;,($a++)*$b and expect an array 1,2,3,4,5. Bummer.


Length 6 Snippet

$a-gt2

OK, pretty simplistic, but this is a continuation of the below concepts. In addition to the usual +-*/ operator overloading, PowerShell comparison operators (-le -eq -gt etc.) are overloaded, too. As are most other "basic" operators.

Let's suppose that $a=3, an int. Then, the above snippet will result in $TRUE as it's comparing "is 3 greater than 2?" So far, so standard. However, let's take $a=(0,1,2,3,4,5) an array of int's from 0 to 5. In this case, the above snippet will result in an array (3,4,5) - that is, it constructed a new array and populated it with all elements of $a that are individually greater than 2. Have a constructed array already and want to know how many elements are equal to 0? Try ($a-eq0).Count. Want the biggest element in the array that's smaller than a certain value? How about ($a-lt4|sort)[-1] (using our "last element" trick from Snippet 4).

This sort of operator overloading continues to other objects, too, not just arrays and ints. $StringA -gt $StringB will categorize the two strings alphabetically. $CharA -gt $CharB calculates based on their ASCII value. And on and on and on. Pretty much any object in PowerShell can be compared like this.

As a bonus, in most cases, if the right-hand operand can be parsed appropriately, you can mix and match types like you can with normal arithmetic operators. As an example, $DateA -lt "2015/12/17" will implicitly parse the right-hand string into a .NET datetime object to calculate comparison.

Combined, the Length 5 and Length 6 snippets allow PowerShell codegolf answers to be very loose with type-casting, which cuts out a tremendous amount of bytes.


Length 5 Snippet

$a+$b

"What, really? The plus-sign is what you're showcasing? Phaw!" OK, OK, put down your torches and pitchforks, and hear me out. I'm showcasing operator overloading. "Well, so what, plenty of other languages have that! Plus, you showed that for your Length-1 Snippet!" Yeah, but that needs to also be coupled with PowerShell's powerful implicit casting and implicit parsing.

Operations like the above snippet in PowerShell take on the characteristics of the left-hand side operand. Suppose $a='123' and $b=4, with the first as a string and the second as an int. With the above snippet, the result will be 1234 as a string. Flip the order $b+$a and PowerShell will implicitly parse the string object to turn it into an int, and the result will be 127 as an int.

While this is powerful, and allows you to abuse plenty of different operators for nefarious codegolf purposes, it has the quirk feature that operators are not commutative. In other words, ($a+$b) -eq ($b+$a) will return False in lots of cases.


Length 4 Snippet

[-1]

A secret weapon used when indexing arrays or strings or the like to retrieve "the last element." We don't even need to know the length of the array. Want the second-to-last element? Use [-2] instead. And so on.

One example where this comes in handy is in finding the maximal of a list of numbers. Suppose we previously stored them in $x. PowerShell already has an alias for Sort-Object as sort, thus, we can do ($x|sort)[-1] to pull out the maximal item from $x, and we don't even care or know how many items are in $x, and it's significantly shorter than the "regular" method of ($x|measure -maximum).Maximum.


Length 3 Snippet

iex

The command iex is an alias for Invoke-Expresssion, and is similar to an eval() style statement. However, it has implications for codegolf in that it can take parameters or pipeline input (because remember, the pipeline hands off objects, not text).

As a simple example, suppose I need to sum the numbers from 1 to 10. I could write 1+2+3+4+5+6+7+8+9+10, but at 20 bytes that's pretty lengthy. I know I can get a range of numbers using the .. range operator, such as 1..10, but now I essentially have an array of integers. I can concatenate them together with the join operator, like so 1..10-join'+', and now I have a string that can be fed into iex as 1..10-join'+'|iex, for 17 bytes. This simple example shows how very complex commands can be dynamically constructed rather than hardcoded, but still be executed as if they were coded directly, and can significantly cut down on byte-count.


Length 2 Snippet

$_

This was already introduced below in the Length-1 snippet, but it's important enough to reiterate here. Another strong suit that gives PowerShell advantages in codegolfing is the concept of automatic variables. That is, variables that are implicitly created in the background by the system. Here, the $_ variable stands for "the current object in the pipeline." Essentially, it's a variable that is a dynamic placeholder for whatever object we're currently manipulating.

In the example loop 1..1e4|%{$_%5}, the $_ variable first holds the integer 1, then 2, then 3, etc. The power is more evident when dealing with a collection of different objects - $_ could be a string, an int, a custom PSObject holding the entire Windows System Event Log, a TCP/IP socket object, etc., all dynamically typed as the situation changes.


Length 1 Snippet

%

The other answer used a pipe | for the Length-1 snippet, and that's probably the most important 1-symbol snippet for 99% of use cases, but the % is functionally way more powerful for codegolf purposes, and introduces two important concepts.

The first is one of PowerShell's hidden codegolf weapons, aliasing, which significantly cuts down code length. Here, the % character is a standard alias for ForEach-Object, and allows us to create loops with very little code overhead.

The second is operator overloading. In PowerShell, as in other languages, the % operator stands for modulo -- 3%2 will return 1 as an example. However, thanks to a strongly/weakly typed system (more on that later), and strong syntax requirements, the same character serves double-duty.

For example, 1..1e4|%{$_%5} is a loop that will generate and output a 123401234012340... string that's 10,000 characters long (with newlines in between, more on that later).

I've already rambled at length about the differences between ForEach and ForEach-Object, so I won't redo that here.


Factoid

Windows PowerShell had its origins over a dozen years ago (and actually just had its 9-year release anniversary; the original release was 14/Nov/2006) as Monad and the Microsoft Shell. I highly recommend reading the Monad Manifesto, originally published in August of 2002, for an amazing insight into the development process and reasoning behind naming conventions and features that developed to make PowerShell what it is today.

Bonus Factoid -- Even from the very beginning, there was pushback from hardcore users regarding the name change from Monad to PowerShell, including some pundits calling it a fad that would never catch on.

\$\endgroup\$
14
\$\begingroup\$

HAML (HTML Abstraction Markup Language

Factoid

Haml (HTML abstraction markup language) is based on one primary principle: markup should be beautiful. It’s not just beauty for beauty’s sake either; Haml accelerates and simplifies template creation down to veritable haiku.

I'm partly doing this because I'm interested to see how many votes this could get around half a year after the original post ;)

Length 1 Snippet

%

% is the tag marker for Haml. So if for example %div was used, it would result in <div></div>

Length 2 Snippet

%a

As said above, % is the tag marker for Haml. So the a following the tag would tell Haml that it needs to create a set of tags with a inside like this: <a></a>. The <a> tag defines a hyperlink, which links pages and/or objects together.

Length 3 Snippet

%td

As above, this would form the tags for a table cell - <td></td>. Table Cells need to be prefaced by: 1) a Table tag <table>, 2) The Table Body (this is optional) <tbody>, 3) a Table Row <tr>. You would end up with something like this:

<table>
  <tbody>
    <tr>
      <td>[Content Here]</td>
    </tr>
  </tbody>
</table>

Length 4 Snippet

.a I

As <div> tags are so common, you can leave them off in Haml. The . here indicates that the text that follows will be the CSS Class to apply, then the text after that is placed inside the div. So the above would be:

<div class="a">I</div>

Length 5 snippet

.a#bc

A . defines the CSS Class - as above - but the new feature here is the #. This defines the CSS ID of the element. So the above would equal:

<div class="a" id="bc"></div>

Length 6 Snippet

.a Hi!

The second snippet that actually shows something!

Any plain text that comes after a class or id etc is the content for the tag. So the above code would result in:

<div class="a">Hi!</div>

Length 7 Snippet

%ul %li

Lists! The above is an unordered list (%ul) and then the list items are each specified as %li. So for the above to show something, we could do the following.

%ul %li Number one! %li And Two!

This would result in:

<ul>
    <li>Number One!</li>
    <li>And Two!</li>
</ul>

Length 8 Snippet

%p.a#b c

A paragraph! As before, the % indicates a HTML tag, so the above would be:

<p class="a" id="b">c</p>

A saving of 17 characters - 68% reduction :)

Length 9 Snippet

#a .b.c D

A . is the prefix for a css class, and to join two classes together, simply put the two classes without a space like above - .b.c. So the above equals

<div id="a">
  <div class="b c">
    D
  </div>
</div>

Length 10 Snippet

:style=>""

To insert custom CSS to an element in html, you would generally use style="<!-- css here -->". The Haml variant is as above. You would use it as below:

%p{:style => "color: #fff;"} A Paragraph

Converted to HTML is becomes

<p style="color: #fff;">A Paragraph</p>
\$\endgroup\$
1
14
\$\begingroup\$

Minkolang

Length 6 snippet (try it)

$n$*N.

This multiplies together the numbers in the input. $n reads in all of the numbers from input, $* multiplies together the whole stack, N outputs as a number, and . stops. The linked example has 5 6 0.1 -3 (1+1j) (1-1j) as the input and (-18+0j) as the output, thus proving that Minkolang can handle integers, floats, and complex numbers.

It's also worth noting that Minkolang disregards non-numeric characters. In this example, the input is This5Shows6That0.1non-numeric-3characters(1+1j)are(1-1j)disregarded1. and the output is the same as before.

Length 5 snippet (try it)

od?.O

cat program. o reads in a character from input and pushes its ASCII code onto the stack (0 if the input is empty). d then duplicates the top of stack (the character that was just read in). ? is a conditional trampoline, which jumps the next instruction of the top of stack is not 0. If the input was empty, then the . is not jumped and the program halts. Otherwise, O outputs the top of stack as a character.

Here is a 5-byte solution to reverse cat (try it):

$o$O.

$o reads in the whole input as characters, $O outputs the whole stack as characters, and . halts.

Length 4 snippet (try it)

V  .

Minkolang's spaceship can be boosted across empty space, which is done with V. This enables it to get to the ., where the program halts.

Length 3 snippet (try it)

3@.

This demonstrates the unconditional n-trampoline, @ (its cousins are ! ? &). Minkolang's codebox is toroidal, meaning that when the spaceship goes off any edge, it reappears on the opposite edge. Here, 3@ skips the next three instructions in the direction of travel, namely .3@, in that order. So it lands directly on the ., which stops the program.

Length 2 snippet (try it)

N.

This is the shortest program producing output (and stopping). N pops the top of stack and outputs it as an integer and . stops execution. When the stack is empty, any operation that tries to pop from the stack will pop a 0 as it has a bottomless well of 0s. Thus, N will output 0 (with a trailing space) and then stop.

Length 1 snippet (try it)

<empty space>

The shortest infinite loop in Minkolang. But this one has a catch. Unlike Befunge or ><>, this one loops through time. In fact, any column of empty spaces is a potential infinite loop.

Factoid

Minkolang is a Minkowskian (2+1)D stack-based semi-golfing language. The "Minkowskian (2+1)D" part simply means that there are two dimensions of space and one of time. The spaceship (or program counter, if you prefer) travels through time when it's not traveling through space. This might sound weird, but consider this: you are barely moving, sitting in your chair. Even if you include the motions imparted by the Earth's rotation, the Earth's journey around the Sun, and the Sun's journey around the Milky Way, it's still only a tiny fraction of the speed of light. So you move through time at almost exactly the rate of one second per second. If, however, you are moving through space at the speed of light, then time stops. Likewise, the spaceship in Minkolang moves through time when it can, when it's not moving through space! Any instruction that does not change its direction preserves it, and wherever there is a space that the spaceship is not boosted across, it starts moving through time (represented as the layers of the program).

\$\endgroup\$
14
\$\begingroup\$

Detour

If you're having difficulty understanding any of these concepts (or, more likely, if I'm explaining them poorly), please feel free to try it yourself on the online interpreter which gives a nice visualization of the data moving around. There is also a TIO site but it doesn't have a cell visualization tool

Summary

Detour is a 2D language I made. While most 2D languages revolve around directing the instruction pointer (think ><>, befunge), this one focuses on redirection of data/objects. Each character in the program translates to a cell. Each cell will either simply pass on its contents (NOP), modify its contents and pass it on (operations such as addition), or redirect its contents (e.g. pointing its contents downward). More on this later.

Factoid

Detour got its name from the "control flow" in the language. I often find myself constructing complex paths to make data travel around the existing data flow, hence "Detour". This is the purest form of spaghetti code.

Length 1 Snippet

:

: specifies where input is taken. At the start of the program, all input arguments are pushed to the : cell, and then start moving rightward. If no : cell is found, one is inserted by default somewhere (usually at the top or middle).

Length 2 Snippet

+.

This is a program that adds two numbers and outputs the result. The . outputs its contents; that's pretty simple. The more complex part would be +. + is a binary operator which, as you would expect, adds two numbers. The way it adds them, however, is a little weird. In Detour, an operator that takes multiple operands will wait for all its operands to be in the cell before performing the operation.

So let's say a 3 is pushed into a + cell. That 3 will stay in that cell until a second number is also pushed into the cell. After our program does its thing, eventually a 4 finds its way into the same + cell. Now, it has two operands, and will happily add them together and push the result (7) into the next cell.

In this case, the next cell is .. Once the two input arguments get onto the + cell, their result is pushed to ., which outputs the result and exits the program.

Length 3 Snippet

$<<

Ok, now it's starting to get interesting. < is the decrement operator, so it takes n and pushes n-1 to the next cell. $ is the duplicate operator, it clones its contents, pushing one to the next cell, while the other skips the immediate cell. The first clone usually will then also hit the second cell.

Example:

$<<
4

$<<
 44

$<<
  33

$<<
   23

As you can see, $<< yields n-2, n-1. I use this in my fibonacci sequence answer

Length 4 Snippet

[<,]

Now it starts to get interesting. [] denotes a loop; that is to say, data will pass through it until it is negative or zero. The body of the loop, <, does two things: 1) decrement the number; 2) output it. For example, 4[<,] will output 3210

Length 5 Snippet

[$<<]

Now we get to start combining previous snippets (I know, a bit cheaty, but it's late and I'm tired). Remember how in the length 3 snippet we discussed how n$<< yields (n-2, n-1)? Now imagine if we repeatedly run that process over all generated n until they are all ≤ 0? We get the fibonacci sequence!

Warning: the produced results will be negative. Take this into account before using this sequence for something that may pertain to black holes

Length 6 Snippet

g>d$G+

This calculates, given n, n + (n + 1) / 2. While this is not very useful, it demonstrates an important concept: registers. g stores a value in the register, while G retrieves it. What happens is the number gets stored in g. Then it walks through, getting incremented (>), cut in half (d), then duplicated ($). The new value ((n+1)/2) gets added to the value stored in g (n). This yields n + (n+1)/2. Here we start getting into the complicated stuff that's hard to explain with words, feel free to try it in the interpreter.

Registers are used in my fibonacci sequence answer (the 30-byte solution) to store the value of sqrt(5).

Length 7 Snippet

<Q.
;d<

This is again kind of nonsensical, but demonstrates two key components of Detour.

  1. Control flow (Q)
  2. Recursion (;)

First off, Control Flow.
As mentioned in the intro, control flow in Detour is pretty nonstandard. In Detour, control flow cells manipulate an object's direction or location rather than its value. We have seen some control flow in the form of $ and [].
As in the example, Q conditionally redirects objects: that is, it will move an object depending on the object's value. In Q's case, it will push the object down (put keep it pointed in the same direction) if it is positive, and will push it forward otherwise.

Recursion (;) is another type of control flow. ; will move an object to the start of the program (where the input came through, or more concisely, the location of the : cell).

Combining these two things, we can see what the snippet does

  • take input n
  • decrement it
  • If n >= 0, push it down
    • halve it, then decrement it and move it back to the start (lines wrap around in Detour making ;>d equivalent to >d;)
  • Else, push it forward
    • output it.

This can be translated to the following Python program:

def f(n):
  n -= 1      # <
  if n <= 0:  # Q
    print(n)    # .
  else:       # Q
    n /= 2      # d
    n -= 1      # <
    f(n)        # ;

f(input())

Length 9 Snippet

<Q>S.
;$<

This is a recursive fibonacci definition. S sums up all items pushed to it. The bottom uses the fact that objects can wrap around the edges, so ;$< is identical to $<; with a leading space.

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

Whitespace

Factoid:
It allows Whitespace programs to be hidden in the source code of programs in languages like C.

Length 1

[LF]

A single line feed. This is an Instruction Modification Parameter (IMP), which is the first token to determine which category of commands the code will be executing from. Line Feed corresponds to Flow Control.

Length 2

[space][space]

The [space] IMP corresponds to Stack Manipulation. Two spaces inserts the rest of the line of spaces and tabs encoded as binary onto the stack.

Length 3

[LF][LF][LF]

Once again, [LF] corresponds to Flow Control. Three line feeds in a row terminates the program.

Length 4

[tab][LF][space][space]

[tab][LF] corresponds to I/O. This command outputs the character corresponding to the value at the top of the stack.

Length 5

[space][space][space][tab][LF]

Pushes the number 1 onto the stack. This is an example of how numbers are defined for commands such as the Length 2 snippet: the first bit is the sign bit, with [space] being positive and [tab] negative, then for the rest of the line, [space] is 0 and [tab] is 1.

Length 6

[LF][space][space][tab][tab][LF]

[LF][space][space] is a command to mark a label for jumping/subroutines later, and the rest of the line is encoded as binary as mentioned above. This one defines the label -1.

Length 7

[LF][tab][space][space][tab][space][LF]

[LF][tab][space] is jump-if-zero. This snippet jumps to label 2 if the top of the stack is 0.

Length 8

[tab][LF][tab][tab][tab][LF][space][space]

Let's write some meaningful programs now! This executes a command to read a number from STDIN and print the corresponding ASCII character.

Length 9

[space][space][tab][tab][LF][space][space][LF][space]

[space][space][LF][space] is a command to duplicate the top item on the stack, so this will push the number -1 onto the stack, then duplicate it.

Length 10

[space][space][space][tab][space][LF][tab][LF][space][tab]

Pushes 2 onto the stack, then prints it.

\$\endgroup\$
8
  • 4
    \$\begingroup\$ Update, please? \$\endgroup\$ Dec 15, 2015 at 23:19
  • 2
    \$\begingroup\$ You have already 5 upvotes, could you provide some snippets? \$\endgroup\$
    – nicael
    Dec 30, 2015 at 13:18
  • \$\begingroup\$ @nicael sorry I'm lacking the time... I will delete the entry later the day. \$\endgroup\$
    – Minzkraut
    Dec 30, 2015 at 13:44
  • \$\begingroup\$ @Min Ok, though I don't think it's right to delete. Maybe someone will fill it with snippets. \$\endgroup\$
    – nicael
    Dec 30, 2015 at 13:46
  • \$\begingroup\$ @nicael I could keep the post, but it feels like having upvotes that I shouldn't have :/ \$\endgroup\$
    – Minzkraut
    Dec 30, 2015 at 14:02
14
\$\begingroup\$

Brachylog

Factoid

Brachylog is a declarative logic programming language based on Prolog. Its name is constituted of the prefix brachy- (meaning short, from ancient greek βραχύς) and the suffix -log, to mark its link to Prolog.

Length 1

r

A seemingly simple program, that is useful to understand some fundamental basics about Brachylog (and declarative programming in general): Reverse something.

In Brachylog, the program r is a main predicate consisting of one rule (namely, r). All rules in Brachylog implicitely start with the Input (noted ?) and end with the Output (noted .).

Therefore, our program is really ?r., which can be read as Output is the reverse of the Input. The built-in r - Reverse works on the three main data types of Brachylog: lists, strings and integers.

But more interestingly, it is a relationship that we state with r, not a one-way function like most programming languages. As such, r also works as expected when the Output is ground and the Input is not! It even works if both the input and the output have no value, though that doesn't show well on the online interpreter and with a program limited to one character.

We will continues to see in the next examples that predicates in Brachylog are relationships between variables and are as such much more expressive than traditional imperative function. We can also note that the Input and Output of predicates are merely called that because that's usually how those variables are used, but those are simply names and they don't mean that for example the Input necessarily has to be a ground variable.

Length 2

r?

Now that we know that r is reverse, and that ? is the Input, you can probably guess what this program does: test whether the input is a palindrome or not.

Indeed, r? is really ?r?., which can be read as: Input is the reverse of the Input, and Output is the same as the Input. Since we do not need the Output at all here, the second part of the sentence can be disregarded and we then see that it is indeed a palindromeness checking program.

The program .r would have worked the same if we passed our input through the Output variable.

Length 3

:^a

As you can see from the TIO link, the code above squares each element of the input. ^ being the squaring built-in predicate, and a being Apply, a meta-predicate.

In Brachylog, all predicates have only an input and an output argument. Therefore, when we need to "pass" more than one thing to the predicate, we put them in a list.

This is what we are doing with :, which is also the list separator. By writing :^, we are constructing the list [Input, brachylog_power]. So, just like numbers, strings and lists, we can also put predicates in lists.

Apply takes the last element of its input argument as being a predicate, and queries that predicate each time with an element of the rest of its input argument as input (hence why it is called a meta-predicate). The output of apply accumulates the outputs of the queries. This predicate is usually called map in other languages (maplist in Prolog).

Length 4

:@[f

Continuing on meta-predicates, here is f: Findall. As its name suggests, this will find all valid outputs of a predicate for a specific input.

Here, the input to Findall is the list [Input, brachylog_string_prefix]. The predicate string_prefix @[ is true if its output is a prefix of the input. By running Findall on it, we will obtain all prefixes of ?.

Note that the string in string_prefix only comes from the fact that it is a 2 symbols predicate which starts with @ (which represent operations that are more often done on strings). This predicate of course doesn't only work on strings, but also on integers and lists.

Length 5

:Lc.r

This is probably my favorite Brachylog program (most likely because it is twice as short as the Jelly answer on this challenge!). This is a program which palindromizes its input.

In Brachylog, strings and integers can contain variable characters/digits, just like how lists can contain variables as elements. Therefore, :Lc. means “Output is the result of concatenating the Input and a variable L. Then, we impose with .r that the output reversed is still the output (thus, that the output is a palindrome). This will force Brachylog to unify the variable values of L so that the output is indeed a palindrome.

Length 6

:1f
~c

Here is another example of the use of f - Findall and c - Concatenate.

The first line is the main predicate and states “Find all valid outputs of predicate 1 given the Input as input”. The second line is predicate 1 and states The output, when concatenated, results in the Input.

Here, ~ is a simple control symbol which "flips" the arguments of the following predicate: AcZ means “Z is the result of concatenating the elements of A” whereas A~cZ means “concatenating the elements of Z results in A”.

Therefore the program above will find all possible lists of strings (excluding the ones containing the empty string), which when concatenated will result in the input.

Note that ~c is not a second built-in which does the reverse of c ; it is the same as c, but called with swapped arguments. To convince you of this, rewriting predicate 1 as ,.c?, will result in the same program.

Side note: this program could have been written :{~c}f, which does the exact same thing. Choosing one or the other is mostly a matter of preference.

Length 7

:1y
#p=

This demonstrates another meta-predicate: y - Yield, and a major feature of Brachylog: constraints-based arithmetic.

y - Yield is a meta predicate very similar to f - Findall, the difference between the two being that y will unify its output with the first N outputs of the queried predicate (N being the penultimate element of the input arguments), instead of all of the outputs. This is thus very useful for predicates that have an infinite number of choice points, such as arithmetic series.

In Brachylog, all integer arithmetic is based on constraints. This makes operations on integers very declarative in nature ; if we declare the relationship that X + Y = Z (which in Brachylog would be written as X:Y+Z), then this constraint will hold even if those variables have no ground value. Adding more and more constraints will keep on reducing the search space for the possible values of those variables. Then, the labeling process (using = in Brachylog) will assign values to variables such that they respect all constraints that were applied to them.

#p - constraint_prime is a predicate which constrains its input ? (which is unified with its output .) such that it must be a prime number. Using = - Equals, we can then label that variable so that it takes a ground value. The labeling process will order choice points according to the magnitude of the values, which is why overall this program yields the first N prime numbers, starting from 2.

Length 8

~l<:#pa=

As you can see, this does exactly the same thing as the previous 7 bytes program. This one though is much more easier to describe and understand.

We use ~l to get a list whose length is the Input. We then impose with < that the list must contain integers and must be strictly increasing. Using Apply, :#pa then constrains each integer of the list to be a prime number. We then use = to label the values of that list, which results in a strictly increasing list of prime numbers.

Length 9

#0|@e+:0&

This program computes the digital root of its input.

Just like in Prolog, we can write multiple rules for a single predicate, using |: the first rule #0 constrains the Input = the Ouput to be a single digit. If this is not possible, the second rule @e+:0& will split the input as a list of digits, then sum them and call Predicate 0 (the main predicate) recursively.

\$\endgroup\$
14
\$\begingroup\$

ArnoldC

Factoid:

ArnoldC, a programming language based on Arnold Schwarzenegger's one-liners, was created to "to discover new meanings from the Arnold movies with the means of computer science."

Length 1 snippet:

1

Just like many other languages, ArnoldC considers 1 to be true and 0 to be false.

Length 2 snippet:

""

Two quotation marks are used to make a String.

Length 5 snippet:

CHILL

Chill ends a while loop.

Length 6 snippet:

I LIED

The Arnold quote "I LIED" is equivalent to the value 0

GET UP is the addition operator.

Length 7 snippet:

declaim

The -declaim flag can be passed to the compiler to produce an audio file from the source code.

Length 8 snippet:

BULLSHIT

An else statement to be placed after an if statement.

Length 9 snippet:

GET UP 33

GET UP is the addition operator in ArnoldC, so the above code snippet can increment an integer by 33.

Length 10 snippet:

ENOUGH TALK

ENOUGH TALK is placed after GET TO THE CHOPPER to end the assignment of a variable.

\$\endgroup\$
2
  • 3
    \$\begingroup\$ ENOUGH TALK, DO IT NOW: GET UP! \$\endgroup\$
    – fede s.
    Apr 25, 2016 at 2:42
  • 1
    \$\begingroup\$ Passes through an abandoned answer only to discover it has got 7 total votes with only a "Length 1" snippet. \$\endgroup\$ May 30, 2016 at 7:03
14
\$\begingroup\$

Brain-Flak

Factoid:

In Brain-Flak a one is shorter than zero and multiplying by seven takes more characters than multiplying by eight.

Since Brain-Flak programs must have an even number of characters I have added some programs with extra spaces for the odd length snippets. These are not well golfed intentionally but rather put there in an attempt to give you a little more for your kind upvotes.

Length 2 snippet

<>

It switches to the offstack. As a single program this will always output nothing regardless of the inputs.

Length 3 snippet

{ }

This is the {} nilad it pops top item on the stack and returns its value. As a full program it just removes the last item input.

Length 4 snippet

(())

This program pushes one to the top of the stack. This is the shortest way to express 1 in Brain-Flak.

Length 5 snippet

([ ])

This program pushes the stack height to the top of the stack. At the start of a program it acts like argc.

Length 6 snippet

({}{})

This program adds two numbers.

It pops the top two elements and pushes the sum.

Length 7 snippet

This one requires a -d flag to run so +3 bytes

(This one also doesn't work on try it online)

@ij 

This is the injection flag! (With a space after it because it needs to be length 7)

This halts the program takes a Brain-Flak program from STDIN and runs it as part of the code. Its my favorite flag and (arguably) Brain-Flak's shortest self interpreter. @ij flags can be nested

Length 8 snippet

({}<>)<>

This snippet moves the top of the current stack to the other stack. It is a useful component of many programs. It starts by opening a push with ( pops the first value with {}, moves to the other stack using <> and puts the popped value down using ). When that is done it moves back to the original stack with a <>.

Length 9 snippet

({}[()]) 

(One space after the program makes it 9 characters)

This snippet decrements the top of the stack by one. It works by popping the top of the stack with {} and adding it to the negative of () (-1) and then pushing the result back on the stack.

Length 10 snippet

{({}<>)<>}

This snippet will move values from one stack to another until it encounters a zero. In many programs where it is known that the stack does not contain a zero this is used as a cheap stack reverse.

Length 12 snippet

({}<({}())>)

We've finally gotten long enough snippets that we can show off the usefulness of the <...> monad. This program increments the number underneath the top of the stack, while leaving the TOS intact. This approach can be extended. For example, this will increment the number second from the top of the stack:

({}<({}<({}())>)>)

In general, you can do:

'({}<' * n + <code> + '>)' * n

to run <code> on the number that's n from the top without affecting the rest of the stack.

\$\endgroup\$
4
  • \$\begingroup\$ Unfortunately you won't be able to post as much since brain-flak has to have an even source code length. \$\endgroup\$
    – DJMcMayhem
    Oct 20, 2016 at 19:12
  • \$\begingroup\$ @DJMcMayhem I can use debug flags for the odd ones \$\endgroup\$
    – Wheat Wizard
    Oct 20, 2016 at 19:13
  • \$\begingroup\$ Or you could double everything. I'm not sure how valid that is though \$\endgroup\$
    – DJMcMayhem
    Oct 20, 2016 at 19:15
  • \$\begingroup\$ @DJMcMayhem that would not be valid see: meta.codegolf.stackexchange.com/q/546/31203 \$\endgroup\$
    – MegaTom
    Oct 20, 2016 at 19:25
13
\$\begingroup\$

Prelude

Prelude is an esoteric language with 9 instructions, plus the numeric literals 0 through 9. It was created as an ASCII representation of a music-based language called Fugue, which for some strange reason has not been implemented.

Prelude

Length 5

 v
^#

This is a 2-dimensional code snippet, so I'm not sure if the newline should count. Anyway, what it does is to duplicate the top of the first line's stack. The ^ instruction makes a copy of the top of the above line's stack. v copies the top of the below line's stack. # destroys the number on the top of the stack.

Length 4

3(5)

Everyone loves a stack overflow. The above code pushes infinite amounts of fives onto the stack.

Length 3

9()

This program creates an infinite loop, because infinite loops are very important. 9 pushes the value 9 onto the stack. () is a loop that repeats as long as the top value on the stack of the line where ( is is nonzero.

Length 2

?!

This handy utility finds the ASCII value of a character. The ? command inputs one character and places it atop the stack. At least with the default behavior of the official Python interpreter, input is character-based and output is numeric.

Length 1

!

Prelude is a stack-based language in which each line of the program has a separate stack. The stacks are conveniently supplied with an infinite amount of zeroes. ! is an instruction which outputs the top of the stack. Thus, the program ! outputs 0.

\$\endgroup\$
2
  • \$\begingroup\$ Shouldn't it be an error since the stack is empty? \$\endgroup\$ Jan 19, 2015 at 21:36
  • 1
    \$\begingroup\$ @AdamSpeight The stack is never empty. The stack is initialised to a infinite number of 0. So if you do anything on the empty stack it pops a 0. But then there's still an infinite number of them. Pretty nifty. :) \$\endgroup\$ Jan 19, 2015 at 21:55
13
\$\begingroup\$

Jagl

7 Characters

()(1)GF

In Jagl, F is a recursive flatten. You can have many nested arrays and it will flatten them into one. Another little trick is, if you have an array of numbers (and arrays of numbers and so on), and just want to flatten one deep, you can just use b (the sum function) to do that.

6 Characters

(1(1))

The array definition syntax in Jagl uses spaces to separate items, but in some cases, the spaces can be omitted, reducing the character count of the program. Alternatively, this could be written 1(1)G in this case, to reduce the characters even more.

5 Characters

5r[/B

Computes 5 factorial. Makes a range of 0 to 4 inclusive, increments all of the numbers by one, and pushes the product to stack.

4 Characters

1 2G

It only takes one character to encase the whole stack in an array. Alternatively, using a lowercase g would take up to 2 values from the stack and encase them in an array!

3 Characters

m%p

It only takes three characters to filter an array on the stack for all primes, and print the results

2 Characters

T~

To make a self interpreter in Jagl, all it takes is two characters! (though, it would take 6 to make it loop endlessly)

1 Character

m

The function m in Jagl is the isPrime function, so it only takes a few characters to, say, print the primes from 1 to 1000.

Factoid: Jagl was created as a high school project, and the name stands for Just A Golfing Language

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

Clojure

Clojure is a variant of Lisp which runs on the Java virtual machine and the .Net virtual machine. A cross-compiler is also available which will turn Clojure code into JavaScript, and thus Clojure code can be run on just about any computer. Clojure can be written in a functional style which is what got me interested in it.

Length 1 Snippet

; - comments begin with a semi-colon and run until the end-of-line. This is also a valid (if not particularly interesting :-) one-character program.

Length 2 Snippet

One of the strengths of any Lisp-style language is its built-in support for collections. In Clojure there are three main collection types:

  • Lists, which are groups of values surrounded by parentheses - ()
  • Vectors, which are groups of values surrounded by square braces - []
  • Maps, which are pairs of values surrounded by curly braces - {}

Lists are both a data structure and the basis for all programming because all programs in Clojure consist of Lists of function names and arguments (Lisp was originally an acronym which stood for List Processor). An empty List (()), Vector ([]), or Map ({}) is also a valid (if uninteresting) program.

Length 3 Snippet

Invoking a function in Clojure is done by putting the function name first in a list (also known as a sequence), followed by its arguments. For example, if we have a function named a then we would invoke it as (a), assuming it takes no arguments.

Length 4 Snippet

@user100464's comment got me thinking about quoted forms. A quoted form is introduced with a back-quote character, so

`(a)

is a quoted form which will invoke the function a when the quoted form is executed. (This can also be written as (quote (a))). According to this blog posting by Colin Jones, quoting is "one of the most Lispy of the Lisp features". Colin's blog post goes into a good amount of detail about using quoting in Clojure macro definitions (which IMO is a topic worthy of entire books) - however, let's simply say that you can evaluate a quoted form using the (you guessed it) eval function. So let's say we create a simple function a with

(defn a [] (println "a invoked"))

which we can invoke from the REPL with the "normal" unquoted form

(a)

which prints

a invoked

Cool. Now let's create a quoted form which will execute our function a:

(def quota `(a))

We can then invoke it with

(eval quota)

which prints

a invoked

So at its most basic level quoting allows us to create a form to invoke a function, then keep that form hanging around uninvoked until we want to invoke it. For those familiar with C a quoted form is a bit like a function pointer, allowing you to save up the ability to invoke a function anonymously until you're ready to do so. (Lispers - please don't start in on me. Yes, I know what I just said is hideously inaccurate and nearly-but-not-quite completely wrong. However, it's "lies to children" (ref. Terry Pratchett et al in his "Science of Discworld" series). If you think explaining nuclear physics to wizards is easy, you try it! :-) ((Rant on) And C'ers - please don't take offense. I wrote C et se derivees on a daily basis for over 10 years, Back In The Day. I don't anymore. Why? Simple - Moore's Law won. Due to CPU speed increases execution time has become a DRM issue - i.e. whether a compiled-and-optimized C program takes 0.0001 seconds to execute vs. an ugly, slow interpreted language version of the same program taking 0.1 seconds to execute Doesn't Really Matter - the user pushes Enter and the answer comes out before their finger lifts off the key. My day job is writing boring back-office code for a major retailer using Oracle's PL/SQL language (think "Ada with embedded SQL"). The byte-code interpreter is pretty good - but execution time is absolutely dominated by SQL execution time Every Single Time, so it's not that the PL/SQL byte-code interpreter is so great, it's that the CPU is sufficiently fast and the database is so much the elephant in the room that faster execution of non-database code Doesn't Really Matter. (Rant off) :-).

Length 5 Snippet

An example of invoking a function f with a single argument 1 would look like

(f 1)

Length 6 Snippet

Length 7 Snippet

(recur)

Ooooh! Tail recursion! Oooooh!

OK, now that we've gotten over that - WHAT THE HECK IS TAIL RECURSION?!?!? And I don't actually HAVE a tail - can I still use it?!?

Yes - yes, you can.

Tail recursion is a nice way of saying "Branching back to the start of the function (or some other point) instead of making a time-and-memory-consuming recursive function call". Recursive function calls do nasty things like consuming stack space, which is in limited supply and when it's gone, so's your program.

And oh-by-the-way, in Clojure you have to use tail recursion if you want to do any kind of looping. It's just kind of what you do.

Tail recursion in Clojure is done by using the recur form, which takes a variable number of values (see the Length 11 Snippet below for more information), binds those values to the bindings at the recursion point (say what?!?), and then jumps back to the recursion point. And oh-by-the-way - (recur) must be in tail position. (HUH?!?!?).

OK, let's explain.

First, what's a recursion point? A recursion point is a point in the program you can recurse back to. (Oh, thanks...). No, seriously - there are only two recursion points in Clojure - either the beginning of a function (in other words a (defn... or (fn... form) or the top of a loop (i.e. the (loop... form).

So, why all this agony to do looping? Why not something like (for (= i 0) (<= i 10) (+ i 1))? Recall if you will that, in general, "variables" in Clojure DON'T CHANGE - in other words, variables are really constants. (Clojure cognoscenti: "lies to children", OK?). Thus, you don't (usually) assign a new value to a "variable", and thus you can't do the usual "loop" thing where you change the value of the loop control variable.

So what you do in Clojure is, you re-bind the function-or-loop parameters to new values, then re-run the function-or-loop against those new values. Hopefully, since you're doing recursion (and nobody likes an infinite recurser :-) you've got something in the body of your recursive code which forces the recursion to terminate. If not - well, then you can use your CPU to grill hot dogs... :-)

And, oh yeah - "tail position". There's a really good explanation of it here, but suffice to say that an expression is in tail position if it would be returned from the form - i.e. it's not followed by any other form executions.

Now, in some Lisps tail recursion is performed by executing a form which calls the function the code is currently in. The compiler recognizes this and turns the call into a tail-recursive branch back to the beginning of the function if it can - so you'd see something like

(defn some-func [n]
  (if (< n 10)
    (do                       ; then case
      (printf "loop continues %d\n" n)
      (some-func (inc n)))
    (printf "loop done\n")))  ; else case

where (some-func (inc n)) would be a tail-recursive invocation of some-func.

The problem is that if the recursive form invocation isn't truly in tail position it will still be compiled properly by the compiler (it's valid code, after all) - but it will become a stack-consuming function call, which can cause your program to blow up unexpectedly, and it can be very difficult to figure out what's gone wrong.

Clojure's solution is to use the special recur form to indicate that a tail-recursive loop is desired. The compiler checks to ensure that the recur form is in tail position - i.e. that there are no form invocations which follow it in the loop - and then generates to code to re-bind arguments and branch back to the recursion point. In this manner you're guaranteed to get a truly tail-recursive branch or else you get a compiler error. Thus, in Clojure some-func would be:

(defn some-func [n]
  (if (< n 10)
    (do                       ; then case
      (printf "loop continues %d\n" n)
      (recur (inc n)))
    (printf "loop done\n")))  ; else case

For other examples of the use of (recur) look a bit further down the page to the Length 11 Snippet.

Length 8 Snippet

Length 9 Snippet

Length 10 Snippet

Length 11 Snippet

(sum 1 2 3)

One of the things I like about Clojure is its handling of variable numbers of parameters to a function. Let's say that you want to write a function named sum to sum up a bunch of numbers (which is a completely stupid thing to do in Clojure, as it already has a very nice function called + which does exactly that - so (+ 1 2) returns 3, (+ 1 2 3 4) returns 10, and so on - but we'll do it anyways, not because we're stupid, but because we're writing a snippet to explain a concept :-). Well, golly, you say, if I want to enter (sum 1 2), that's a function which takes two arguments; but if I want to add up three arguments that would be (sum 1 2 3), which would be a different function; and then (sum 1 2 3 4 5 6 7 8 987654321) would be Yet Another Function, etc, ad nauseum. It sure would be nice if there was a way to let a function just take in all the arguments someone wanted to pass, without having to explicitly name them every time. And, of course, there is... :-)

In Clojure you specify a function which takes a variable number of parameters thusly:

(defn a-func [arg1 arg2 & more-args] ... )

This function requires two arguments arg1 and arg2, and accepts an undefined number of additional arguments which are put into a vector and bound to the argument more-args. So let's see how we'd take advantage of this to write a sum function:

(defn sum [n & more-n]
  (loop [ tot     0
          num     n
          rest-n  more-n ]
  (if (> (count rest-n) 0)
    (recur (+ tot num) (first rest-n) (rest rest-n))
    (+ tot num))))

Here we define a function sum which takes at least one argument, named n, and optionally takes a bunch of other arguments which will be lumped together into more-n. Inside the function we create a loop (which is, if you recall, a recursion point) which defines several bindings: tot is the summed total of all the arguments, which will be returned later; 'num', which is the number we're working with right now; and rest-n which is the rest of our numbers.

Note that a slightly more Lisp-y way to define our sum function is to use a "worker" function to do all the actual summation work instead of a loop:

(defn sum-all [tot n more-n]
  (if (> (count more-n) 0)
    (recur (+ tot n) (first more-n) (rest more-n))
    (+ tot n)))

(defn sum [n & more-n]
  (sum-all 0 n more-n))

This version turns the loop of the first version into a separate function, which then recursively re-invokes itself.

So now you know a bit about handling variable numbers of arguments in Clojure.


(Trying to make snippets for a rather verbose language like Clojure is relatively difficult. To quote AC/DC, "I'll tell you, folks, it's harder than it looks...") (And no, I'm not going to play the bagpipes :-)

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Length 4 could be '(1) for an unevaluated list of length 1 \$\endgroup\$
    – user100464
    May 1, 2016 at 3:48
  • \$\begingroup\$ @user100464 - thanks for the interesting idea. :-) \$\endgroup\$ May 1, 2016 at 13:37
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.