mollusk 019f8e3064 Add: julia-0.6.2
Former-commit-id: ccc667cf67d569f3fb3df39aa57c2134755a7551
2018-02-10 10:27:19 -07:00

140 lines
30 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Interfaces · The Julia Language</title><script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-28835595-6', 'auto');
ga('send', 'pageview');
</script><link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css" rel="stylesheet" type="text/css"/><link href="https://fonts.googleapis.com/css?family=Lato|Roboto+Mono" rel="stylesheet" type="text/css"/><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css"/><script>documenterBaseURL=".."</script><script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js" data-main="../assets/documenter.js"></script><script src="../siteinfo.js"></script><script src="../../versions.js"></script><link href="../assets/highlightjs/default.css" rel="stylesheet" type="text/css"/><link href="../assets/documenter.css" rel="stylesheet" type="text/css"/></head><body><nav class="toc"><a href="../index.html"><img class="logo" src="../assets/logo.png" alt="The Julia Language logo"/></a><h1>The Julia Language</h1><select id="version-selector" onChange="window.location.href=this.value" style="visibility: hidden"></select><form class="search" action="../search.html"><input id="search-query" name="q" type="text" placeholder="Search docs"/></form><ul><li><a class="toctext" href="../index.html">Home</a></li><li><span class="toctext">Manual</span><ul><li><a class="toctext" href="introduction.html">Introduction</a></li><li><a class="toctext" href="getting-started.html">Getting Started</a></li><li><a class="toctext" href="variables.html">Variables</a></li><li><a class="toctext" href="integers-and-floating-point-numbers.html">Integers and Floating-Point Numbers</a></li><li><a class="toctext" href="mathematical-operations.html">Mathematical Operations and Elementary Functions</a></li><li><a class="toctext" href="complex-and-rational-numbers.html">Complex and Rational Numbers</a></li><li><a class="toctext" href="strings.html">Strings</a></li><li><a class="toctext" href="functions.html">Functions</a></li><li><a class="toctext" href="control-flow.html">Control Flow</a></li><li><a class="toctext" href="variables-and-scoping.html">Scope of Variables</a></li><li><a class="toctext" href="types.html">Types</a></li><li><a class="toctext" href="methods.html">Methods</a></li><li><a class="toctext" href="constructors.html">Constructors</a></li><li><a class="toctext" href="conversion-and-promotion.html">Conversion and Promotion</a></li><li class="current"><a class="toctext" href="interfaces.html">Interfaces</a><ul class="internal"><li><a class="toctext" href="#man-interface-iteration-1">Iteration</a></li><li><a class="toctext" href="#Indexing-1">Indexing</a></li><li><a class="toctext" href="#man-interface-array-1">Abstract Arrays</a></li></ul></li><li><a class="toctext" href="modules.html">Modules</a></li><li><a class="toctext" href="documentation.html">Documentation</a></li><li><a class="toctext" href="metaprogramming.html">Metaprogramming</a></li><li><a class="toctext" href="arrays.html">Multi-dimensional Arrays</a></li><li><a class="toctext" href="linear-algebra.html">Linear algebra</a></li><li><a class="toctext" href="networking-and-streams.html">Networking and Streams</a></li><li><a class="toctext" href="parallel-computing.html">Parallel Computing</a></li><li><a class="toctext" href="dates.html">Date and DateTime</a></li><li><a class="toctext" href="interacting-with-julia.html">Interacting With Julia</a></li><li><a class="toctext" href="running-external-programs.html">Running External Programs</a></li><li><a class="toctext" href="calling-c-and-fortran-code.html">Calling C and Fortran Code</a></li><li><a class="toctext" href="handling-operating-system-variation.html">Handling Operating System Variation</a></li><li><a class="toctext" href="environment-variables.html">Environment Variables</a></li><li><a class="toctext" href="embedding.html">Embedding Julia</a></li><li><a class="toctext" href="packages.html">Packages</a></li><li><a class="toctext" href="profile.html">Profiling</a></li><li><a class="toctext" href="stacktraces.html">Stack Traces</a></li><li><a class="toctext" href="performance-tips.html">Performance Tips</a></li><li><a class="toctext" href="workflow-tips.html">Workflow Tips</a></li><li><a class="toctext" href="style-guide.html">Style Guide</a></li><li><a class="toctext" href="faq.html">Frequently Asked Questions</a></li><li><a class="toctext" href="noteworthy-differences.html">Noteworthy Differences from other Languages</a></li><li><a class="toctext" href="unicode-input.html">Unicode Input</a></li></ul></li><li><span class="toctext">Standard Library</span><ul><li><a class="toctext" href="../stdlib/base.html">Essentials</a></li><li><a class="toctext" href="../stdlib/collections.html">Collections and Data Structures</a></li><li><a class="toctext" href="../stdlib/math.html">Mathematics</a></li><li><a class="toctext" href="../stdlib/numbers.html">Numbers</a></li><li><a class="toctext" href="../stdlib/strings.html">Strings</a></li><li><a class="toctext" href="../stdlib/arrays.html">Arrays</a></li><li><a class="toctext" href="../stdlib/parallel.html">Tasks and Parallel Computing</a></li><li><a class="toctext" href="../stdlib/linalg.html">Linear Algebra</a></li><li><a class="toctext" href="../stdlib/constants.html">Constants</a></li><li><a class="toctext" href="../stdlib/file.html">Filesystem</a></li><li><a class="toctext" href="../stdlib/io-network.html">I/O and Network</a></li><li><a class="toctext" href="../stdlib/punctuation.html">Punctuation</a></li><li><a class="toctext" href="../stdlib/sort.html">Sorting and Related Functions</a></li><li><a class="toctext" href="../stdlib/pkg.html">Package Manager Functions</a></li><li><a class="toctext" href="../stdlib/dates.html">Dates and Time</a></li><li><a class="toctext" href="../stdlib/iterators.html">Iteration utilities</a></li><li><a class="toctext" href="../stdlib/test.html">Unit Testing</a></li><li><a class="toctext" href="../stdlib/c.html">C Interface</a></li><li><a class="toctext" href="../stdlib/libc.html">C Standard Library</a></li><li><a class="toctext" href="../stdlib/libdl.html">Dynamic Linker</a></li><li><a class="toctext" href="../stdlib/profile.html">Profiling</a></li><li><a class="toctext" href="../stdlib/stacktraces.html">StackTraces</a></li><li><a class="toctext" href="../stdlib/simd-types.html">SIMD Support</a></li></ul></li><li><span class="toctext">Developer Documentation</span><ul><li><a class="toctext" href="../devdocs/reflection.html">Reflection and introspection</a></li><li><span class="toctext">Documentation of Julia&#39;s Internals</span><ul><li><a class="toctext" href="../devdocs/init.html">Initialization of the Julia runtime</a></li><li><a class="toctext" href="../devdocs/ast.html">Julia ASTs</a></li><li><a class="toctext" href="../devdocs/types.html">More about types</a></li><li><a class="toctext" href="../devdocs/object.html">Memory layout of Julia Objects</a></li><li><a class="toctext" href="../devdocs/eval.html">Eval of Julia code</a></li><li><a class="toctext" href="../devdocs/callconv.html">Calling Conventions</a></li><li><a class="toctext" href="../devdocs/compiler.html">High-level Overview of the Native-Code Generation Process</a></li><li><a class="toctext" href="../devdocs/functions.html">Julia Functions</a></li><li><a class="toctext" href="../devdocs/cartesian.html">Base.Cartesian</a></li><li><a class="toctext" href="../devdocs/meta.html">Talking to the compiler (the <code>:meta</code> mechanism)</a></li><li><a class="toctext" href="../devdocs/subarrays.html">SubArrays</a></li><li><a class="toctext" href="../devdocs/sysimg.html">System Image Building</a></li><li><a class="toctext" href="../devdocs/llvm.html">Working with LLVM</a></li><li><a class="toctext" href="../devdocs/stdio.html">printf() and stdio in the Julia runtime</a></li><li><a class="toctext" href="../devdocs/boundscheck.html">Bounds checking</a></li><li><a class="toctext" href="../devdocs/locks.html">Proper maintenance and care of multi-threading locks</a></li><li><a class="toctext" href="../devdocs/offset-arrays.html">Arrays with custom indices</a></li><li><a class="toctext" href="../devdocs/libgit2.html">Base.LibGit2</a></li><li><a class="toctext" href="../devdocs/require.html">Module loading</a></li></ul></li><li><span class="toctext">Developing/debugging Julia&#39;s C code</span><ul><li><a class="toctext" href="../devdocs/backtraces.html">Reporting and analyzing crashes (segfaults)</a></li><li><a class="toctext" href="../devdocs/debuggingtips.html">gdb debugging tips</a></li><li><a class="toctext" href="../devdocs/valgrind.html">Using Valgrind with Julia</a></li><li><a class="toctext" href="../devdocs/sanitizers.html">Sanitizer support</a></li></ul></li></ul></li></ul></nav><article id="docs"><header><nav><ul><li>Manual</li><li><a href="interfaces.html">Interfaces</a></li></ul><a class="edit-page" href="https://github.com/JuliaLang/julia/tree/d386e40c17d43b79fc89d3e579fc04547241787c/doc/src/manual/interfaces.md"><span class="fa"></span> Edit on GitHub</a></nav><hr/><div id="topbar"><span>Interfaces</span><a class="fa fa-bars" href="#"></a></div></header><h1><a class="nav-anchor" id="Interfaces-1" href="#Interfaces-1">Interfaces</a></h1><p>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.</p><h2><a class="nav-anchor" id="man-interface-iteration-1" href="#man-interface-iteration-1">Iteration</a></h2><table><tr><th>Required methods</th><th> </th><th>Brief description</th></tr><tr><td><code>start(iter)</code></td><td> </td><td>Returns the initial iteration state</td></tr><tr><td><code>next(iter, state)</code></td><td> </td><td>Returns the current item and the next state</td></tr><tr><td><code>done(iter, state)</code></td><td> </td><td>Tests if there are any items remaining</td></tr><tr><td><strong>Important optional methods</strong></td><td><strong>Default definition</strong></td><td><strong>Brief description</strong></td></tr><tr><td><code>iteratorsize(IterType)</code></td><td><code>HasLength()</code></td><td>One of <code>HasLength()</code>, <code>HasShape()</code>, <code>IsInfinite()</code>, or <code>SizeUnknown()</code> as appropriate</td></tr><tr><td><code>iteratoreltype(IterType)</code></td><td><code>HasEltype()</code></td><td>Either <code>EltypeUnknown()</code> or <code>HasEltype()</code> as appropriate</td></tr><tr><td><code>eltype(IterType)</code></td><td><code>Any</code></td><td>The type the items returned by <code>next()</code></td></tr><tr><td><code>length(iter)</code></td><td>(<em>undefined</em>)</td><td>The number of items, if known</td></tr><tr><td><code>size(iter, [dim...])</code></td><td>(<em>undefined</em>)</td><td>The number of items in each dimension, if known</td></tr></table><table><tr><th>Value returned by <code>iteratorsize(IterType)</code></th><th>Required Methods</th></tr><tr><td><code>HasLength()</code></td><td><code>length(iter)</code></td></tr><tr><td><code>HasShape()</code></td><td><code>length(iter)</code> and <code>size(iter, [dim...])</code></td></tr><tr><td><code>IsInfinite()</code></td><td>(<em>none</em>)</td></tr><tr><td><code>SizeUnknown()</code></td><td>(<em>none</em>)</td></tr></table><table><tr><th>Value returned by <code>iteratoreltype(IterType)</code></th><th>Required Methods</th></tr><tr><td><code>HasEltype()</code></td><td><code>eltype(IterType)</code></td></tr><tr><td><code>EltypeUnknown()</code></td><td>(<em>none</em>)</td></tr></table><p>Sequential iteration is implemented by the methods <a href="../stdlib/collections.html#Base.start"><code>start()</code></a>, <a href="../stdlib/collections.html#Base.done"><code>done()</code></a>, and <a href="../stdlib/collections.html#Base.next"><code>next()</code></a>. Instead of mutating objects as they are iterated over, Julia provides these three methods to keep track of the iteration state externally from the object. The <code>start(iter)</code> method returns the initial state for the iterable object <code>iter</code>. That state gets passed along to <code>done(iter, state)</code>, which tests if there are any elements remaining, and <code>next(iter, state)</code>, which returns a tuple containing the current element and an updated <code>state</code>. The <code>state</code> object can be anything, and is generally considered to be an implementation detail private to the iterable object.</p><p>Any object defines these three methods is iterable and can be used in the <a href="../stdlib/collections.html#lib-collections-iteration-1">many functions that rely upon iteration</a>. It can also be used directly in a <code>for</code> loop since the syntax:</p><pre><code class="language-julia">for i in iter # or &quot;for i = iter&quot;
# body
end</code></pre><p>is translated into:</p><pre><code class="language-julia">state = start(iter)
while !done(iter, state)
(i, state) = next(iter, state)
# body
end</code></pre><p>A simple example is an iterable sequence of square numbers with a defined length:</p><pre><code class="language-jldoctest">julia&gt; struct Squares
count::Int
end
julia&gt; Base.start(::Squares) = 1
julia&gt; Base.next(S::Squares, state) = (state*state, state+1)
julia&gt; Base.done(S::Squares, state) = state &gt; S.count
julia&gt; Base.eltype(::Type{Squares}) = Int # Note that this is defined for the type
julia&gt; Base.length(S::Squares) = S.count</code></pre><p>With only <a href="../stdlib/collections.html#Base.start"><code>start</code></a>, <a href="../stdlib/collections.html#Base.next"><code>next</code></a>, and <a href="../stdlib/collections.html#Base.done"><code>done</code></a> definitions, the <code>Squares</code> type is already pretty powerful. We can iterate over all the elements:</p><pre><code class="language-jldoctest">julia&gt; for i in Squares(7)
println(i)
end
1
4
9
16
25
36
49</code></pre><p>We can use many of the builtin methods that work with iterables, like <a href="../stdlib/collections.html#Base.in"><code>in()</code></a>, <a href="../stdlib/math.html#Base.mean"><code>mean()</code></a> and <a href="../stdlib/math.html#Base.std"><code>std()</code></a>:</p><pre><code class="language-jldoctest">julia&gt; 25 in Squares(10)
true
julia&gt; mean(Squares(100))
3383.5
julia&gt; std(Squares(100))
3024.355854282583</code></pre><p>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 <code>Squares</code> sequence will always be <code>Int</code>. By extending the <a href="../stdlib/collections.html#Base.eltype"><code>eltype()</code></a> 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 <a href="../stdlib/arrays.html#Base.length-Tuple{AbstractArray}"><code>length()</code></a>, too.</p><p>Now, when we ask Julia to <a href="../stdlib/collections.html#Base.collect-Tuple{Any}"><code>collect()</code></a> all the elements into an array it can preallocate a <code>Vector{Int}</code> of the right size instead of blindly <a href="../stdlib/collections.html#Base.push!"><code>push!</code></a>ing each element into a <code>Vector{Any}</code>:</p><pre><code class="language-jldoctest">julia&gt; collect(Squares(10))&#39; # transposed to save space
1×10 RowVector{Int64,Array{Int64,1}}:
1 4 9 16 25 36 49 64 81 100</code></pre><p>While we can rely upon generic implementations, we can also extend specific methods where we know there is a simpler algorithm. For example, there&#39;s a formula to compute the sum of squares, so we can override the generic iterative version with a more performant solution:</p><pre><code class="language-jldoctest">julia&gt; Base.sum(S::Squares) = (n = S.count; return n*(n+1)*(2n+1)÷6)
julia&gt; sum(Squares(1803))
1955361914</code></pre><p>This is a very common pattern throughout the Julia standard library: 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.</p><h2><a class="nav-anchor" id="Indexing-1" href="#Indexing-1">Indexing</a></h2><table><tr><th>Methods to implement</th><th>Brief description</th></tr><tr><td><code>getindex(X, i)</code></td><td><code>X[i]</code>, indexed element access</td></tr><tr><td><code>setindex!(X, v, i)</code></td><td><code>X[i] = v</code>, indexed assignment</td></tr><tr><td><code>endof(X)</code></td><td>The last index, used in <code>X[end]</code></td></tr></table><p>For the <code>Squares</code> iterable above, we can easily compute the <code>i</code>th element of the sequence by squaring it. We can expose this as an indexing expression <code>S[i]</code>. To opt into this behavior, <code>Squares</code> simply needs to define <a href="../stdlib/arrays.html#Base.getindex-Tuple{Type,Vararg{Any,N} where N}"><code>getindex()</code></a>:</p><pre><code class="language-jldoctest">julia&gt; function Base.getindex(S::Squares, i::Int)
1 &lt;= i &lt;= S.count || throw(BoundsError(S, i))
return i*i
end
julia&gt; Squares(100)[23]
529</code></pre><p>Additionally, to support the syntax <code>S[end]</code>, we must define <a href="../stdlib/collections.html#Base.endof"><code>endof()</code></a> to specify the last valid index:</p><pre><code class="language-jldoctest">julia&gt; Base.endof(S::Squares) = length(S)
julia&gt; Squares(23)[end]
529</code></pre><p>Note, though, that the above <em>only</em> defines <a href="../stdlib/arrays.html#Base.getindex-Tuple{Type,Vararg{Any,N} where N}"><code>getindex()</code></a> with one integer index. Indexing with anything other than an <code>Int</code> will throw a <a href="../stdlib/base.html#Base.MethodError"><code>MethodError</code></a> saying that there was no matching method. In order to support indexing with ranges or vectors of <code>Int</code>s, separate methods must be written:</p><pre><code class="language-jldoctest">julia&gt; Base.getindex(S::Squares, i::Number) = S[convert(Int, i)]
julia&gt; Base.getindex(S::Squares, I) = [S[i] for i in I]
julia&gt; Squares(10)[[3,4.,5]]
3-element Array{Int64,1}:
9
16
25</code></pre><p>While this is starting to support more of the <a href="arrays.html#man-array-indexing-1">indexing operations supported by some of the builtin types</a>, there&#39;s still quite a number of behaviors missing. This <code>Squares</code> sequence is starting to look more and more like a vector as we&#39;ve added behaviors to it. Instead of defining all these behaviors ourselves, we can officially define it as a subtype of an <a href="../stdlib/arrays.html#Core.AbstractArray"><code>AbstractArray</code></a>.</p><h2><a class="nav-anchor" id="man-interface-array-1" href="#man-interface-array-1">Abstract Arrays</a></h2><table><tr><th>Methods to implement</th><th> </th><th>Brief description</th></tr><tr><td><code>size(A)</code></td><td> </td><td>Returns a tuple containing the dimensions of <code>A</code></td></tr><tr><td><code>getindex(A, i::Int)</code></td><td> </td><td>(if <code>IndexLinear</code>) Linear scalar indexing</td></tr><tr><td><code>getindex(A, I::Vararg{Int, N})</code></td><td> </td><td>(if <code>IndexCartesian</code>, where <code>N = ndims(A)</code>) N-dimensional scalar indexing</td></tr><tr><td><code>setindex!(A, v, i::Int)</code></td><td> </td><td>(if <code>IndexLinear</code>) Scalar indexed assignment</td></tr><tr><td><code>setindex!(A, v, I::Vararg{Int, N})</code></td><td> </td><td>(if <code>IndexCartesian</code>, where <code>N = ndims(A)</code>) N-dimensional scalar indexed assignment</td></tr><tr><td><strong>Optional methods</strong></td><td><strong>Default definition</strong></td><td><strong>Brief description</strong></td></tr><tr><td><code>IndexStyle(::Type)</code></td><td><code>IndexCartesian()</code></td><td>Returns either <code>IndexLinear()</code> or <code>IndexCartesian()</code>. See the description below.</td></tr><tr><td><code>getindex(A, I...)</code></td><td>defined in terms of scalar <code>getindex()</code></td><td><a href="arrays.html#man-array-indexing-1">Multidimensional and nonscalar indexing</a></td></tr><tr><td><code>setindex!(A, I...)</code></td><td>defined in terms of scalar <code>setindex!()</code></td><td><a href="arrays.html#man-array-indexing-1">Multidimensional and nonscalar indexed assignment</a></td></tr><tr><td><code>start()</code>/<code>next()</code>/<code>done()</code></td><td>defined in terms of scalar <code>getindex()</code></td><td>Iteration</td></tr><tr><td><code>length(A)</code></td><td><code>prod(size(A))</code></td><td>Number of elements</td></tr><tr><td><code>similar(A)</code></td><td><code>similar(A, eltype(A), size(A))</code></td><td>Return a mutable array with the same shape and element type</td></tr><tr><td><code>similar(A, ::Type{S})</code></td><td><code>similar(A, S, size(A))</code></td><td>Return a mutable array with the same shape and the specified element type</td></tr><tr><td><code>similar(A, dims::NTuple{Int})</code></td><td><code>similar(A, eltype(A), dims)</code></td><td>Return a mutable array with the same element type and size <em>dims</em></td></tr><tr><td><code>similar(A, ::Type{S}, dims::NTuple{Int})</code></td><td><code>Array{S}(dims)</code></td><td>Return a mutable array with the specified element type and size</td></tr><tr><td><strong>Non-traditional indices</strong></td><td><strong>Default definition</strong></td><td><strong>Brief description</strong></td></tr><tr><td><code>indices(A)</code></td><td><code>map(OneTo, size(A))</code></td><td>Return the <code>AbstractUnitRange</code> of valid indices</td></tr><tr><td><code>Base.similar(A, ::Type{S}, inds::NTuple{Ind})</code></td><td><code>similar(A, S, Base.to_shape(inds))</code></td><td>Return a mutable array with the specified indices <code>inds</code> (see below)</td></tr><tr><td><code>Base.similar(T::Union{Type,Function}, inds)</code></td><td><code>T(Base.to_shape(inds))</code></td><td>Return an array similar to <code>T</code> with the specified indices <code>inds</code> (see below)</td></tr></table><p>If a type is defined as a subtype of <code>AbstractArray</code>, it inherits a very large set of rich behaviors including iteration and multidimensional indexing built on top of single-element access. See the <a href="arrays.html#man-multi-dim-arrays-1">arrays manual page</a> and <a href="../stdlib/arrays.html#lib-arrays-1">standard library section</a> for more supported methods.</p><p>A key part in defining an <code>AbstractArray</code> subtype is <a href="../stdlib/arrays.html#Base.IndexStyle"><code>IndexStyle</code></a>. Since indexing is such an important part of an array and often occurs in hot loops, it&#39;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 <code>IndexLinear()</code> and <code>IndexCartesian()</code>. 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.</p><p>This distinction determines which scalar indexing methods the type must define. <code>IndexLinear()</code> arrays are simple: just define <code>getindex(A::ArrayType, i::Int)</code>. When the array is subsequently indexed with a multidimensional set of indices, the fallback <code>getindex(A::AbstractArray, I...)()</code> efficiently converts the indices into one linear index and then calls the above method. <code>IndexCartesian()</code> arrays, on the other hand, require methods to be defined for each supported dimensionality with <code>ndims(A)</code> <code>Int</code> indices. For example, the built-in <a href="../stdlib/arrays.html#Base.SparseArrays.SparseMatrixCSC"><code>SparseMatrixCSC</code></a> type only supports two dimensions, so it just defines <code>getindex(A::SparseMatrixCSC, i::Int, j::Int)</code>. The same holds for <code>setindex!()</code>.</p><p>Returning to the sequence of squares from above, we could instead define it as a subtype of an <code>AbstractArray{Int, 1}</code>:</p><pre><code class="language-jldoctest">julia&gt; struct SquaresVector &lt;: AbstractArray{Int, 1}
count::Int
end
julia&gt; Base.size(S::SquaresVector) = (S.count,)
julia&gt; Base.IndexStyle(::Type{&lt;:SquaresVector}) = IndexLinear()
julia&gt; Base.getindex(S::SquaresVector, i::Int) = i*i</code></pre><p>Note that it&#39;s very important to specify the two parameters of the <code>AbstractArray</code>; the first defines the <a href="../stdlib/collections.html#Base.eltype"><code>eltype()</code></a>, and the second defines the <a href="../stdlib/arrays.html#Base.ndims"><code>ndims()</code></a>. That supertype and those three methods are all it takes for <code>SquaresVector</code> to be an iterable, indexable, and completely functional array:</p><pre><code class="language-jldoctest">julia&gt; s = SquaresVector(7)
7-element SquaresVector:
1
4
9
16
25
36
49
julia&gt; s[s .&gt; 20]
3-element Array{Int64,1}:
25
36
49
julia&gt; s \ [1 2; 3 4; 5 6; 7 8; 9 10; 11 12; 13 14]
1×2 Array{Float64,2}:
0.305389 0.335329
julia&gt; s ⋅ s # dot(s, s)
4676</code></pre><p>As a more complicated example, let&#39;s define our own toy N-dimensional sparse-like array type built on top of <a href="../stdlib/collections.html#Base.Dict"><code>Dict</code></a>:</p><pre><code class="language-jldoctest">julia&gt; struct SparseArray{T,N} &lt;: AbstractArray{T,N}
data::Dict{NTuple{N,Int}, T}
dims::NTuple{N,Int}
end
julia&gt; SparseArray{T}(::Type{T}, dims::Int...) = SparseArray(T, dims);
julia&gt; SparseArray{T,N}(::Type{T}, dims::NTuple{N,Int}) = SparseArray{T,N}(Dict{NTuple{N,Int}, T}(), dims);
julia&gt; Base.size(A::SparseArray) = A.dims
julia&gt; Base.similar(A::SparseArray, ::Type{T}, dims::Dims) where {T} = SparseArray(T, dims)
julia&gt; Base.getindex(A::SparseArray{T,N}, I::Vararg{Int,N}) where {T,N} = get(A.data, I, zero(T))
julia&gt; Base.setindex!(A::SparseArray{T,N}, v, I::Vararg{Int,N}) where {T,N} = (A.data[I] = v)</code></pre><p>Notice that this is an <code>IndexCartesian</code> array, so we must manually define <a href="../stdlib/arrays.html#Base.getindex-Tuple{Type,Vararg{Any,N} where N}"><code>getindex()</code></a> and <a href="../stdlib/arrays.html#Base.setindex!-Tuple{AbstractArray,Any,Vararg{Any,N} where N}"><code>setindex!()</code></a> at the dimensionality of the array. Unlike the <code>SquaresVector</code>, we are able to define <a href="../stdlib/arrays.html#Base.setindex!-Tuple{AbstractArray,Any,Vararg{Any,N} where N}"><code>setindex!()</code></a>, and so we can mutate the array:</p><pre><code class="language-jldoctest">julia&gt; A = SparseArray(Float64, 3, 3)
3×3 SparseArray{Float64,2}:
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
julia&gt; fill!(A, 2)
3×3 SparseArray{Float64,2}:
2.0 2.0 2.0
2.0 2.0 2.0
2.0 2.0 2.0
julia&gt; A[:] = 1:length(A); A
3×3 SparseArray{Float64,2}:
1.0 4.0 7.0
2.0 5.0 8.0
3.0 6.0 9.0</code></pre><p>The result of indexing an <code>AbstractArray</code> can itself be an array (for instance when indexing by a <code>Range</code>). The <code>AbstractArray</code> fallback methods use <a href="../stdlib/arrays.html#Base.similar-Tuple{AbstractArray}"><code>similar()</code></a> to allocate an <code>Array</code> 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:</p><pre><code class="language-jldoctest">julia&gt; A[1:2,:]
2×3 SparseArray{Float64,2}:
1.0 4.0 7.0
2.0 5.0 8.0</code></pre><p>In this example it is accomplished by defining <code>Base.similar{T}(A::SparseArray, ::Type{T}, dims::Dims)</code> to create the appropriate wrapped array. (Note that while <code>similar</code> supports 1- and 2-argument forms, in most case you only need to specialize the 3-argument form.) For this to work it&#39;s important that <code>SparseArray</code> is mutable (supports <code>setindex!</code>). Defining <code>similar()</code>, <code>getindex()</code> and <code>setindex!()</code> for <code>SparseArray</code> also makes it possible to <a href="../stdlib/base.html#Base.copy"><code>copy()</code></a> the array:</p><pre><code class="language-jldoctest">julia&gt; copy(A)
3×3 SparseArray{Float64,2}:
1.0 4.0 7.0
2.0 5.0 8.0
3.0 6.0 9.0</code></pre><p>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 the standard library for <code>AbstractArrays</code>:</p><pre><code class="language-jldoctest">julia&gt; A[SquaresVector(3)]
3-element SparseArray{Float64,1}:
1.0
4.0
9.0
julia&gt; dot(A[:,1],A[:,2])
32.0</code></pre><p>If you are defining an array type that allows non-traditional indexing (indices that start at something other than 1), you should specialize <code>indices</code>. You should also specialize <a href="../stdlib/arrays.html#Base.similar-Tuple{AbstractArray}"><code>similar</code></a> so that the <code>dims</code> argument (ordinarily a <code>Dims</code> size-tuple) can accept <code>AbstractUnitRange</code> objects, perhaps range-types <code>Ind</code> of your own design. For more information, see <a href="../devdocs/offset-arrays.html#Arrays-with-custom-indices-1">Arrays with custom indices</a>.</p><footer><hr/><a class="previous" href="conversion-and-promotion.html"><span class="direction">Previous</span><span class="title">Conversion and Promotion</span></a><a class="next" href="modules.html"><span class="direction">Next</span><span class="title">Modules</span></a></footer></article></body></html>