Wolfram Language Shorten Source Code

By Xah Lee. Date: .

Here's ways to shorten WolframLang code. Some tips are general for writing great short programs, other tips are for shorten character count for Wolfram tweet tap http://wolframtap.com but is not good coding style. The tips here are ordered by their general usefulness for good code. (tips here are similar to ideas of “minification”, “code golf”, “obfuscation”, but here i avoid any hacking or abusing language syntax or semantic flaws.)

Use @ instead of []

For function with 1 arg, such as f[x], use f@x.

For example, Cube[{3,4,5}] can be written as Cube@{3,4,5}

Use &

Make a lot use of & for Function, and /@ for Map.

(#1 + 1 & ) /@ Range[3] === Function[x, x + 1] /@ Range[3]

Note, when you use &, you need to pay attention to the operator precedence. For safest, use parenthesis like this: ((code)&)

Avoid Pattern Matching

Avoid pattern matching whenever you can. Use Function form (& and #) The code is not just shorter, but much faster, and more precise in behavior. For example:

f=(#1+#2 &);

Use ##

Use SlotSequence, {##} instead of {#1,#2,#3}

Array is shorter than Table

because you avoid the dummy variable names, and avoid extra curly brackets for each dimention.

Table[f[{x, y, z}], {x, -2, 2}, {y, 0, 2}, {z, -1, 1}] ===
Array[f[{##1}] & , {5, 3, 3}, {-2, 0, -1}]

Alias Long Function Name

This is to save character count. Useful when long function names are needed more than once.


WolframLang Guide