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).
8 Answers
NOTE: The below are correct as of Julia 1.4.1
A few tricks to save a few characters
- 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 typea\b
instead ofdiv(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÷
fordiv
, as noted by Alex A. - 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. - (sometimes) Store small fixed-size vectors as separate variables. For instance, rather than
a=split("Hi there"," ")
, you may be able to avoida[1]
anda[2]
by usinga,b=split("Hi there"," ")
, which can be referenced asa
andb
, 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. - 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. - 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 asx>1||"Hi"
, saving a character (so long as the return of the boolean isn't important). - Don't use contains to check presence of character in string - if you're restricted to the basic ASCII, use
in('^',s)
rather thancontains(s,"^")
. If you can use other characters, you can save a bit more with'^'∈s
, but note that∈
is 3 bytes in UTF-8. - Looking for minimum/maximum values in an array? Don't use minimum or maximum - rather than using
minimum(x)
ormaximum(x)
, usemin(x...)
ormax(x...)
, to shave one character off your code.Alternatively, if you know all elements ofx
will be non-negative, useminabs(x)
ormaxabs(x)
- 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.
- 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"
, typer"match^ this"m
, saving three characters. - 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 inAny[[1,2]]
. At one stage, curly braces could be used as an alternate notation ({[1,2]}
), but this has been discontinued. - 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. - Need a number converted to a string? Use
"$(s[i])"
orfor expressions or multi-character variables, anddec(s[i])
"$i"
for single-character variables. - Use
union
or∪
instead ofunique
-union(s)
will do the same thing asunique(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 inunion
. In some circumstances, for single-character variables, you can save another byte usings∪s
(thanks, MarcMush, fors∪s
). - 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 ofA
and the middle value, you might writeA[(k=end)÷2]
. This can also work in multiple dimensions, and for index iterators -A[(k=1:end;)]
will give you an iterator fork=1:length(A)
, which can be handy when you also want to useA
. 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 expressionA[]
is equivalent toA[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 thanflipud(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 writingcond?A=B:1
rather thancond&&(A=B)
, orcond?1:A=B
rather thancond||(A=B)
. Note that the1
, here, is a dummy value. - the?:
notation now requires spaces around?
and:
.
-
6\$\begingroup\$ Oh how I would love that first trick in Python. \$\endgroup\$– seequJun 4, 2014 at 18:04
-
\$\begingroup\$ You can split on spaces using simply
split("Hi there")
since the pattern argument defaults to a space. \$\endgroup\$– Alex A.Jul 15, 2015 at 14:23 -
\$\begingroup\$ @AlexA. - I know, but it's not the point of the tip, and the tip applies equally well either way. \$\endgroup\$– Glen OJul 15, 2015 at 14:28
-
1\$\begingroup\$ @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. \$\endgroup\$– Glen OApr 21, 2020 at 0:24
-
1\$\begingroup\$ @MarcMush - thank you, I've made some edits based on your feedback. I'll have to revisit with more tips, soon. \$\endgroup\$– Glen OMay 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
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
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
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.
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 unorderedDict
type. Thus, it requires costlycollect(keys())
andcollect(values())
and potentially also acat
and asort
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.Use map
map
is a great alternative to looping. Be aware of the difference betweenmap
andmap!
and exploit the in-place functionality of the latter when you can.Use mapreduce
mapreduce
extends the functionality of map even further and can be a significant byte-saver.Anonymous functions are great! ..especially when passed to the aforementioned
map
functions.Cumulative array functions
cumprod
,cumsum
, the flavorfulcummin
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)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 usingA[:,2]
Use the single-line notation for functions Instead of
function f(x) begin ... end
you can often simplify tof(x)=(...)
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
-
3\$\begingroup\$ How on Earth is "use the ternary operator" somewhat specific to Julia? It's relevant to every language which has it. \$\endgroup\$ Mar 17, 2014 at 17:40
-
5\$\begingroup\$ 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. \$\endgroup\$ Mar 17, 2014 at 18:04
-
3\$\begingroup\$ 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? \$\endgroup\$ Mar 17, 2014 at 18:50
-
3\$\begingroup\$ Well, hey, at least you're an equal-opportunity curmudgeon. ヘ( ̄ー ̄ヘ) \$\endgroup\$ Mar 17, 2014 at 19:14
-
1\$\begingroup\$ 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). \$\endgroup\$– Glen OJul 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
Female and Male Sequences (binary)
Case Permutation (unary)
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
andend
. This is also true forend
occurring after a close paren, i.e.)end
.Perform integer division using
÷
rather thandiv()
or overloading an operator. Note that÷
is worth 2 bytes in UTF-8.Use
vec()
orA[:]
(for some arrayA
) rather thanreshape()
whenever possible.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) n=read(STDIN,Int);n^2-1
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.
- Don't type
return
f(x)=x+4
is identical to but shorter thanf(x)=return x+4
. Julia always returns the result of the last statement. - 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 charactersg.(x,[y])
-- 9 characters
1. Use @b_str
to store lists
returning an array of UInt8
s (ranging 0-127 in ascii)
for example
[99,100]
-- 8 charactersb"cd"
-- 5 characters
and using Unicode characters:
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)
-
can take 1 or 2 arguments Try it online!~
can kinda take 1 or 2 arguments Try it online!+
can take 1 or more arguments Try it online!*
can take 2 or more arguments Try it online!
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
)>
(and>
,==
...) can be splat without parenthesis,~
also but not in the function definition Try it online!+
(and*
,++
) interpretsa+b+c
as+(a,b,c)
rather than(a+b)+c
<
(and>
,==
...) has a short-circuiting behaviour Try it online!
-
2\$\begingroup\$
r=1:n;@.println(r*n^r)
seems to work too, it also beats the other solutions. \$\endgroup\$ Aug 20, 2021 at 7:32