Tips for golfing in Julia

What general tips do you have for golfing in Julia? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Julia (e.g. "remove comments" is not an answer).

NOTE: The below are correct as of Julia 1.4.1

A few tricks to save a few characters

1. Overload operators with frequently used binary functions. For example, if you need to do a lot of integer divisions, and no need for inverse division, use \ =div, and you can then type a\b instead of div(a,b). Note the space - this is necessary to avoid it parsing as a "=" operator. Also note that, if overloaded at REPL prompt level, use (\)=Base.(\) or \ =Base. \ to reset it. NOTE: some functions have existing UTF-8 operators pre-defined, such as ÷ for div, as noted by Alex A.
2. Use ^ with strings for conditional output. That is, rather than a>0?"Hi":"", use "Hi"^(a>0) to save one byte, or for boolean a, use "Hi"^a to save three bytes.
3. (sometimes) Store small fixed-size vectors as separate variables. For instance, rather than a=split("Hi there"," "), you may be able to avoid a[1] and a[2] by using a,b=split("Hi there"," "), which can be referenced as a and b, saving three bytes for each use, at the cost of just two extra characters at assignment. Obviously, do not do this if you can work with vector operations.
4. Don't use isempty for Arrays, Tuples, or Strings - instead, use ==[] for arrays and ==() for tuples; similarly, for the negative, use !=[] and !=(). For strings, use =="" for empty, but use >"" for not-empty, as "" is lexicographically before any other string and it saves one byte.
5. Use the right short-circuit boolean operator in place of "if". It might be a bit less Julia-specific, but it is worth bearing in mind. x<=1&&"Hi" can be written as x>1||"Hi", saving a character (so long as the return of the boolean isn't important).
6. Don't use contains to check presence of character in string - if you're restricted to the basic ASCII, use in('^',s) rather than contains(s,"^"). If you can use other characters, you can save a bit more with '^'∈s, but note that ∈ is 3 bytes in UTF-8.
7. Looking for minimum/maximum values in an array? Don't use minimum or maximum - rather than using minimum(x) or maximum(x), use min(x...) or max(x...), to shave one character off your code. Alternatively, if you know all elements of x will be non-negative, use minabs(x) or maxabs(x)
8. Where possible and permitted by the challenge, use an actual newline instead of \n - note that this will make your code harder to read, and may mean that you need to provide an "ungolfed" version to make it possible for people to actually understand it.
9. Put options after the regex string - if you want to have a regex string in multiline mode, for example, don't type r"(?m)match^ this", type r"match^ this"m, saving three characters.
10. Where possible, use array concatenation instead of push!, unshift!, append!, or prepend! - for normal arrays, this can be done easily. For arrays of type Any with array elements, you will need the type Any, as in Any[[1,2]]. At one stage, curly braces could be used as an alternate notation ({[1,2]}), but this has been discontinued.
11. Don't use collect to convert a string into a char array - instead of collect(A), use [A...], which will do the same thing and save 4 bytes.
12. Need a number converted to a string? Use "$(s[i])" or dec(s[i]) for expressions or multi-character variables, and "$i" for single-character variables.
13. Use union or ∪ instead of unique - union(s) will do the same thing as unique(s), and save a byte in the process. If you can use non-ASCII characters, then ∪(s) will do the same thing, and ∪ only costs 3 bytes instead of the 5 bytes in union. In some circumstances, for single-character variables, you can save another byte using s∪s (thanks, MarcMush, for s∪s).
14. Use array indexing to get the size of an array or string - when you use end within array indexing, it automatically gets converted to the length of the array/string. This can be handy when you want to collect the length while doing certain operations. For example, if you need the length of A and the middle value, you might write A[(k=end)÷2]. This can also work in multiple dimensions, and for index iterators - A[(k=1:end;)] will give you an iterator for k=1:length(A), which can be handy when you also want to use A. Note that the assignment must occur in brackets, with a semicolon (such as (k=end;)) if no operation is done outside the brackets. (thanks to MarcMush for identifying a workaround for keywords in array indexing)

Outdated tricks that worked at some point, but no longer do:

Access first element of Array with [] - for arrays, the expression A[] is equivalent to A[1]. Note that this does not work for Strings if you wish to get the first character, or for Tuples. - A[] no longer works.

Reverse 1-D arrays using flipud - reverse(x) is one byte longer than flipud(x) and will perform the same operation, so the latter is better. - flipud is no longer in Base.

Use ?: instead of && or || for conditional assignment - that is, if you want to perform an assignment only on some condition, you can save one byte by writing cond?A=B:1 rather than cond&&(A=B), or cond?1:A=B rather than cond||(A=B). Note that the 1, here, is a dummy value. - the ?: notation now requires spaces around ? and :.

• Oh how I would love that first trick in Python. Jun 4, 2014 at 18:04
• You can split on spaces using simply split("Hi there") since the pattern argument defaults to a space. Jul 15, 2015 at 14:23
• @AlexA. - I know, but it's not the point of the tip, and the tip applies equally well either way. Jul 15, 2015 at 14:28
• @HenriqueFerrolho - thanks, I'll revisit the list soon (hopefully by this weekend) to figure out which ones are now outdated, as well as whether there are any notable new tricks. Apr 21, 2020 at 0:24
• @MarcMush - thank you, I've made some edits based on your feedback. I'll have to revisit with more tips, soon. May 14, 2021 at 6:06

Redefine operators to define functions

Redefining operators can save a lot of bytes in parentheses and commas.

Recursive unary operators

For a unary example, compare the following recursive implementations of the Fibonacci sequence:

F(n)=n>1?F(n-1)+F(n-2):n # 24 bytes
!n=n>1?!~-n+!(n-2):n     # 20 bytes
!n=n>1?!~-n+!~-~-n:n     # 20 bytes


Try it online!

The redefined operator retains its initial precedence.

Note that we could not simply swap out ! in favor of ~, since ~ is already defined for integers, while ! is only defined for Booleans.

Binary operators

Even without recursion, redefining an operator is shorter than defining a binary function. Compare the following definitions of a simple divisibility test.

f(x,y)=x==0?y==0:y%x==0 # 23 bytes
(x,y)->x==0?y==0:y%x==0 # 23 bytes
x->y->x==0?y==0:y%x==0  # 22 bytes
x\y=x==0?y==0:y%x==0    # 20 bytes


Try it online!

Recursive binary operators

The following illustrates how to redefine a binary operator to compute the Ackermann function:

A(m,n)=m>0?A(m-1,n<1||A(m,n-1)):n+1    # 35 bytes
^ =(m,n)->m>0?(m-1)^(n<1||m^~-n):n+1   # 36 bytes
| =(m,n)->m>0?m-1|(n<1||m|~-n):n+1     # 34 bytes
m\n=m>0?~-m\(n<1||m\~-n):n+1           # 28 bytes


Try it online!

Note that ^ is even longer than using a regular identifier, since its precedence is too high.

As mentioned before

m|n=m>0?m-1|(n<1||m|~-n):n+1           # 28 bytes


would not work for integer arguments, since | is already defined in this case. The definition for integers can be changed with

m::Int|n::Int=m>0?m-1|(n<1||m|~-n):n+1 # 38 bytes


but that's prohibitively long. However, it does work if we pass a float as left argument and an integer as right argument.

1. Don't be too easily seduced by factor(n) The tempting base library function factor(n) has a fatal flaw: it returns the factorization of your integer in an unordered Dict type. Thus, it requires costly collect(keys()) and collect(values()) and potentially also a cat and a sort to get the data you wanted out of it. In many cases, it may be cheaper to just factor by trial division. Sad, but true.

2. Use map map is a great alternative to looping. Be aware of the difference between map and map! and exploit the in-place functionality of the latter when you can.

3. Use mapreduce mapreduce extends the functionality of map even further and can be a significant byte-saver.

4. Anonymous functions are great! ..especially when passed to the aforementioned map functions.

5. Cumulative array functions cumprod, cumsum, the flavorful cummin and the other similarly named functions enable cumulative operations along a specified dimension of an n-dimensional array. (Or *un*specified if the array is 1-d)

6. Short notation for Any When you want to select all of a particular dimension of a multi-dimensional array (or Dict), e.g. A[Any,2], you can save bytes by using A[:,2]

7. Use the single-line notation for functions Instead of function f(x) begin ... end you can often simplify to f(x)=(...)

8. Use the ternary operator It can be a space-saver for single-expression If-Then-Else constructions. Caveats: While possible in some other languages, you cannot omit the portion after the colon in Julia. Also, the operator is expression-level in Julia, so you cannot use it for conditional execution of whole blocks of code.
if x<10 then true else false end vs
x<10?true:false

• How on Earth is "use the ternary operator" somewhat specific to Julia? It's relevant to every language which has it. Mar 17, 2014 at 17:40
• It's relevant that it has it. Many languages also have map, anonymous or pure functions, some kind of shorthand for any/all, cumulative functions, etc. If we were to reduce every tips thread to only the features absolutely unique to that language, there would be very little tips content. Mar 17, 2014 at 18:04
• Gosh, only all the functional ones for starters, where everything returns a value so a ternary op would be redundant. If you must have specific examples: Go, Haskell, Scala, Lua, VB, Prolog, PL/SQL...even Python didn't for many versions. Of the near-dozen languages whose tips threads mention their ternary operator is there some reason you only chose to come be provincial in mine? Mar 17, 2014 at 18:50
• Well, hey, at least you're an equal-opportunity curmudgeon. ヘ(￣ー￣ヘ) Mar 17, 2014 at 19:14
• Might I suggest adjusting tip 3? mapreduce is longer than either mapfoldl or mapfoldr, and can have varying behaviour depending on implementation. mapfoldl and mapfoldr are left- and right-associative (respectively) consistently, and thus are a better choice. This also applies more generally to reduce (use foldl or foldr). Jul 15, 2015 at 9:07

Iterate over functions

This is also possible in other languages, but usually longer than the straightforward method. However, Julia's ability to redefine its unary and binary operators make it quite golfy.

For example, to generate the addition, subtraction, multiplication and division table for the natural numbers from 1 to 10, one could use

[x|y for x=1:10,y=1:10,| =(+,-,*,÷)]


which redefines the binary operator | as +, -, * and ÷, then computes x|y for each operation and x and y in the desired ranges.

This works for unary operators as well. For example, to compute complex numbers 1+2i, 3-4i, -5+6i and -7-8i, their negatives, their complex conjugates and their multiplicative inverses, one could use

[~x for~=(+,-,conj,inv),x=(1+2im,3-4im,-5+6im,-7-8im)]


which redefines the unary operator ~ as +, -, conj and inv, then computes ~x for all desired complex numbers.

Examples in actual contests

1. Keywords can sometimes immediately follow constants without the need for a space or semicolon. For example:

n->(for i=1:n n-=1end;n)


Note the lack of a space between 1 and end. This is also true for end occurring after a close paren, i.e. )end.

2. Perform integer division using ÷ rather than div() or overloading an operator. Note that ÷ is worth 2 bytes in UTF-8.

3. Use vec() or A[:] (for some array A) rather than reshape() whenever possible.

4. Create functions rather than full programs when allowed in the challenge rules. It's shorter to define a function which accepts input rather than defining variables by reading from stdin. For example:

n->(n^2-1)

5. Variables can be incremented inside the argument to a function. For example, the following is my answer to the Find the Next 1-Sparse Binary Number challenge:

n->(while contains(bin(n+=1),"11")end;n)


This is shorter than incrementing n inside of the loop.

1. Don't type return f(x)=x+4 is identical to but shorter than f(x)=return x+4. Julia always returns the result of the last statement.
2. Use = instead of in. [x for x in 1:4] is 3 characters longer than, but equivalent to [x for x=1:4]

Use Broadcasting function calls.

Introduced in Julia 0.5. It is like map, but uses less characters, and does broadcasting behavour over it's args -- which means you can write less lambda's to deal with things.

Rather than:

• map(f,x) -- 8 characters.
• f.(x) -- 5 characters

Better still:

• map(a->g(a,y),x) -- 16 characters
• g.(x,[y]) -- 9 characters

1. Use @b_str to store lists

returning an array of UInt8s (ranging 0-127 in ascii)

for example

• [99,100] -- 8 characters
• b"cd" -- 5 characters

and using Unicode caracters:

• b"🐢" -- 4 characters, 7 bytes
• [240,159,144,162] -- way more

2. Avoid loops, use .|> or @.

Very often, .|> or broadcasting is shorter:

• r=1:n;@.print(r*n^r)
• 1:n.|>i->print(i*n^i)
• @.print((1:n)n^(1:n))
• print.((1:n).*n.^(1:n))
• [print(i*n^i) for i=1:n]
• for i=1:n print(i*n^i)end

3. Choose the right function to override

• depending on the number of arguments it can take without parenthesis (useful for recursive functions)

• depending on their operator precedence

• > and < are useful, with a lower precedence than + Example with <
• ~ has a very low precedence, lower than <, =>, &&... Example
• ^ has the highest precedence, battling with unary operators (-x^-y == -(x^(-y)))
• * has the precedence of an unary operator when the * is omitted (2x^2abs(y)a == 2*(x^(2*abs(y)*a)))
• some quirky operators

• ~ is the only operator that can be placed directly before a = (for example ~=length)
• > can be splat without parenthesis Try it online!
• + (and *, ++) interprets a+b+c as +(a,b,c) rather than (a+b)+c
• < (and >, ==...) has a short-circuiting behaviour Try it online!
• r=1:n;@.println(r*n^r) seems to work too, it also beats the other solutions. Aug 20, 2021 at 7:32