Is Julia the next R



A lot of the power and extensibility in Julia comes from a collection of informal interfaces. By extending a few specific methods to work for a custom type, objects of that type not only receive those functionalities, but they are also able to be used in other methods that are written to generically build upon those behaviors.


Required methodsBrief description
Returns either a tuple of the first item and initial state or if empty
Returns either a tuple of the next item and next state or if no items remain
Important optional methodsDefault definitionBrief description
One of , , , or as appropriate
Either or as appropriate
The type of the first entry of the tuple returned by
(undefined)The number of items, if known
(undefined)The number of items in each dimension, if known
Value returned by Required Methods
Value returned by Required Methods

Sequential iteration is implemented by the function. Instead of mutating objects as they are iterated over, Julia iterators may keep track of the iteration state externally from the object. The return value from iterate is always either a tuple of a value and a state, or if no elements remain. The state object will be passed back to the iterate function on the next iteration and is generally considered an implementation detail private to the iterable object.

Any object that defines this function is iterable and can be used in the many functions that rely upon iteration. It can also be used directly in a loop since the syntax:

is translated into:

A simple example is an iterable sequence of square numbers with a defined length:

With only definition, the type is already pretty powerful. We can iterate over all the elements:

We can use many of the builtin methods that work with iterables, like , or and from the standard library module:

There are a few more methods we can extend to give Julia more information about this iterable collection. We know that the elements in a sequence will always be . By extending the method, we can give that information to Julia and help it make more specialized code in the more complicated methods. We also know the number of elements in our sequence, so we can extend , too:

Now, when we ask Julia to all the elements into an array it can preallocate a of the right size instead of blindly ing each element into a :

While we can rely upon generic implementations, we can also extend specific methods where we know there is a simpler algorithm. For example, there's a formula to compute the sum of squares, so we can override the generic iterative version with a more performant solution:

This is a very common pattern throughout Julia Base: a small set of required methods define an informal interface that enable many fancier behaviors. In some cases, types will want to additionally specialize those extra behaviors when they know a more efficient algorithm can be used in their specific case.

It is also often useful to allow iteration over a collection in reverse order by iterating over . To actually support reverse-order iteration, however, an iterator type needs to implement for . (Given , the underling iterator of type is .) In our example, we would implement methods:


Methods to implementBrief description
, indexed element access
, indexed assignment
The first index
The last index, used in

For the iterable above, we can easily compute the th element of the sequence by squaring it. We can expose this as an indexing expression . To opt into this behavior, simply needs to define :

Additionally, to support the syntax , we must define to specify the last valid index. It is recommended to also define to specify the first valid index:

Note, though, that the above only defines with one integer index. Indexing with anything other than an will throw a saying that there was no matching method. In order to support indexing with ranges or vectors of s, separate methods must be written:

While this is starting to support more of the indexing operations supported by some of the builtin types, there's still quite a number of behaviors missing. This sequence is starting to look more and more like a vector as we've added behaviors to it. Instead of defining all these behaviors ourselves, we can officially define it as a subtype of an .

Abstract Arrays

Methods to implementBrief description
Returns a tuple containing the dimensions of
(if ) Linear scalar indexing
(if , where ) N-dimensional scalar indexing
(if ) Scalar indexed assignment
(if , where ) N-dimensional scalar indexed assignment
Optional methodsDefault definitionBrief description
Returns either or . See the description below.
defined in terms of scalar Multidimensional and nonscalar indexing
defined in terms of scalar Multidimensional and nonscalar indexed assignment
defined in terms of scalar Iteration
Number of elements
Return a mutable array with the same shape and element type
Return a mutable array with the same shape and the specified element type
Return a mutable array with the same element type and size dims
Return a mutable array with the specified element type and size
Non-traditional indicesDefault definitionBrief description
Return the of valid indices
Return a mutable array with the specified indices (see below)
Return an array similar to with the specified indices (see below)

If a type is defined as a subtype of , it inherits a very large set of rich behaviors including iteration and multidimensional indexing built on top of single-element access. See the arrays manual page and the Julia Base section for more supported methods.

A key part in defining an subtype is . Since indexing is such an important part of an array and often occurs in hot loops, it's important to make both indexing and indexed assignment as efficient as possible. Array data structures are typically defined in one of two ways: either it most efficiently accesses its elements using just one index (linear indexing) or it intrinsically accesses the elements with indices specified for every dimension. These two modalities are identified by Julia as and . Converting a linear index to multiple indexing subscripts is typically very expensive, so this provides a traits-based mechanism to enable efficient generic code for all array types.

This distinction determines which scalar indexing methods the type must define. arrays are simple: just define . When the array is subsequently indexed with a multidimensional set of indices, the fallback efficiently converts the indices into one linear index and then calls the above method. arrays, on the other hand, require methods to be defined for each supported dimensionality with indices. For example, from the standard library module, only supports two dimensions, so it just defines . The same holds for .

Returning to the sequence of squares from above, we could instead define it as a subtype of an :

Note that it's very important to specify the two parameters of the ; the first defines the , and the second defines the . That supertype and those three methods are all it takes for to be an iterable, indexable, and completely functional array:

As a more complicated example, let's define our own toy N-dimensional sparse-like array type built on top of :

Notice that this is an array, so we must manually define and at the dimensionality of the array. Unlike the , we are able to define , and so we can mutate the array:

The result of indexing an can itself be an array (for instance when indexing by an ). The fallback methods use to allocate an of the appropriate size and element type, which is filled in using the basic indexing method described above. However, when implementing an array wrapper you often want the result to be wrapped as well:

In this example it is accomplished by defining to create the appropriate wrapped array. (Note that while supports 1- and 2-argument forms, in most case you only need to specialize the 3-argument form.) For this to work it's important that is mutable (supports ). Defining , and for also makes it possible to the array:

In addition to all the iterable and indexable methods from above, these types can also interact with each other and use most of the methods defined in Julia Base for :

If you are defining an array type that allows non-traditional indexing (indices that start at something other than 1), you should specialize . You should also specialize so that the argument (ordinarily a size-tuple) can accept objects, perhaps range-types of your own design. For more information, see Arrays with custom indices.

Strided Arrays

Methods to implementBrief description
Return the distance in memory (in number of elements) between adjacent elements in each dimension as a tuple. If is an , this should return an empty tuple.
Return the native address of an array.
Optional methodsDefault definitionBrief description
Return the distance in memory (in number of elements) between adjacent elements in dimension k.

A strided array is a subtype of whose entries are stored in memory with fixed strides. Provided the element type of the array is compatible with BLAS, a strided array can utilize BLAS and LAPACK routines for more efficient linear algebra routines. A typical example of a user-defined strided array is one that wraps a standard with additional structure.

Warning: do not implement these methods if the underlying storage is not actually strided, as it may lead to incorrect results or segmentation faults.

Here are some examples to demonstrate which type of arrays are strided and which are not:

Customizing broadcasting

Methods to implementBrief description
Broadcasting behavior of
Allocation of output container
Optional methods
Precedence rules for mixing styles
Declaration of the indices of , as per .
Convert to an object that has and supports indexing
Bypassing default machinery
Custom implementation of
Custom implementation of , specializing on
Custom implementation of , specializing on
Override the default lazy behavior within a fused expression
Override the computation of the lazy broadcast's axes

Broadcasting is triggered by an explicit call to or , or implicitly by "dot" operations like or . Any object that has and supports indexing can participate as an argument in broadcasting, and by default the result is stored in an . This basic framework is extensible in three major ways:

  • Ensuring that all arguments support broadcast
  • Selecting an appropriate output array for the given set of arguments
  • Selecting an efficient implementation for the given set of arguments

Not all types support and indexing, but many are convenient to allow in broadcast. The function is called on each argument to broadcast, allowing it to return something different that supports and indexing. By default, this is the identity function for all s and s — they already support and indexing. For a handful of other types (including but not limited to types themselves, functions, special singletons like and , and dates), returns the argument wrapped in a to act as a 0-dimensional "scalar" for the purposes of broadcasting. Custom types can similarly specialize to define their shape, but they should follow the convention that . A notable exception is ; strings are special-cased to behave as scalars for the purposes of broadcast even though they are iterable collections of their characters (see Strings for more).

The next two steps (selecting the output array and implementation) are dependent upon determining a single answer for a given set of arguments. Broadcast must take all the varied types of its arguments and collapse them down to just one output array and one implementation. Broadcast calls this single answer a "style." Every broadcastable object each has its own preferred style, and a promotion-like system is used to combine these styles into a single answer — the "destination style".

Broadcast Styles

is the abstract type from which all broadcast styles are derived. When used as a function it has two possible forms, unary (single-argument) and binary. The unary variant states that you intend to implement specific broadcasting behavior and/or output type, and do not wish to rely on the default fallback .

To override these defaults, you can define a custom for your object:

In some cases it might be convenient not to have to define , in which case you can leverage one of the general broadcast wrappers:

  • can be used for arbitrary types.
  • is preferred if is an .
  • For that only support a certain dimensionality, create a subtype of (see below).

When your broadcast operation involves several arguments, individual argument styles get combined to determine a single that controls the type of the output container. For more details, see below.

Selecting an appropriate output array

The broadcast style is computed for every broadcasting operation to allow for dispatch and specialization. The actual allocation of the result array is handled by , using the Broadcasted object as its first argument.

The fallback definition is

However, if needed you can specialize on any or all of these arguments. The final argument is a lazy representation of a (potentially fused) broadcast operation, a object. For these purposes, the most important fields of the wrapper are and , describing the function and argument list, respectively. Note that the argument list can — and often does — include other nested wrappers.

For a complete example, let's say you have created a type, , that stores an array and a single character:

You might want broadcasting to preserve the "metadata." First we define

This means we must also define a corresponding method:

From these definitions, one obtains the following behavior:

Extending broadcast with custom implementations

In general, a broadcast operation is represented by a lazy container that holds onto the function to be applied alongside its arguments. Those arguments may themselves be more nested containers, forming a large expression tree to be evaluated. A nested tree of containers is directly constructed by the implicit dot syntax; is transiently represented by , for example. This is invisible to users as it is immediately realized through a call to , but it is this container that provides the basis for broadcast's extensibility for authors of custom types. The built-in broadcast machinery will then determine the result type and size based upon the arguments, allocate it, and then finally copy the realization of the object into it with a default method. The built-in fallback and methods similarly construct a transient representation of the operation so they can follow the same codepath. This allows custom array implementations to provide their own specialization to customize and optimize broadcasting. This is again determined by the computed broadcast style. This is such an important part of the operation that it is stored as the first type parameter of the type, allowing for dispatch and specialization.

For some types, the machinery to "fuse" operations across nested levels of broadcasting is not available or could be done more efficiently incrementally. In such cases, you may need or want to evaluate as if it had been written , where the inner operation is evaluated before tackling the outer operation. This sort of eager operation is directly supported by a bit of indirection; instead of directly constructing objects, Julia lowers the fused expression to . Now, by default, just calls the constructor to create the lazy representation of the fused expression tree, but you can choose to override it for a particular combination of function and arguments.

As an example, the builtin objects use this machinery to optimize pieces of broadcasted expressions that can be eagerly evaluated purely in terms of the start, step, and length (or stop) instead of computing every single element. Just like all the other machinery, also computes and exposes the combined broadcast style of its arguments, so instead of specializing on , you can specialize on for any combination of style, function, and arguments.

For example, the following definition supports the negation of ranges:

Extending in-place broadcasting

In-place broadcasting can be supported by defining the appropriate method. Because you might want to specialize either on or the specific subtype of , to avoid ambiguities between packages we recommend the following convention.

If you wish to specialize on a particular style , define a method for

Optionally, with this form you can also specialize on the type of .

If instead you want to specialize on the destination type without specializing on , then you should define a method with the following signature:

This leverages a fallback implementation of that converts the wrapper into a . Consequently, specializing on has lower precedence than methods that specialize on .

Similarly, you can completely override out-of-place broadcasting with a method.

Working with objects

In order to implement such a or , method, of course, you must work with the wrapper to compute each element. There are two main ways of doing so:

  • recomputes the potentially nested operation into a single function and flat list of arguments. You are responsible for implementing the broadcasting shape rules yourself, but this may be helpful in limited situations.
  • Iterating over the of the and using indexing with the resulting object to compute the result.

Writing binary broadcasting rules

The precedence rules are defined by binary calls:

where is the you want to choose for outputs involving arguments of and . For example,

indicates that "wins" over zero-dimensional arrays (the output container will be a tuple). It is worth noting that you do not need to (and should not) define both argument orders of this call; defining one is sufficient no matter what order the user supplies the arguments in.

For types, defining a supersedes the fallback choice, . and the abstract supertype, , store the dimensionality as a type parameter to support specialized array types that have fixed dimensionality requirements.

"loses" to any other that has been defined because of the following methods:

You do not need to write binary rules unless you want to establish precedence for two or more non- types.

If your array type does have fixed dimensionality requirements, then you should subtype . For example, the sparse array code has the following definitions:

Whenever you subtype , you also need to define rules for combining dimensionalities, by creating a constructor for your style that takes a argument. For example:

These rules indicate that the combination of a with 0- or 1-dimensional arrays yields another , that its combination with a 2-dimensional array yields a , and anything of higher dimensionality falls back to the dense arbitrary-dimensional framework. These rules allow broadcasting to keep the sparse representation for operations that result in one or two dimensional outputs, but produce an for any other dimensionality.

PreviousConversion and PromotionNextModules