140 lines
30 KiB
HTML
140 lines
30 KiB
HTML
|
<!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="toc
|
|||
|
# 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> struct Squares
|
|||
|
count::Int
|
|||
|
end
|
|||
|
|
|||
|
julia> Base.start(::Squares) = 1
|
|||
|
|
|||
|
julia> Base.next(S::Squares, state) = (state*state, state+1)
|
|||
|
|
|||
|
julia> Base.done(S::Squares, state) = state > S.count
|
|||
|
|
|||
|
julia> Base.eltype(::Type{Squares}) = Int # Note that this is defined for the type
|
|||
|
|
|||
|
julia> 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> 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> 25 in Squares(10)
|
|||
|
true
|
|||
|
|
|||
|
julia> mean(Squares(100))
|
|||
|
3383.5
|
|||
|
|
|||
|
julia> 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> collect(Squares(10))' # 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'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> Base.sum(S::Squares) = (n = S.count; return n*(n+1)*(2n+1)÷6)
|
|||
|
|
|||
|
julia> 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> function Base.getindex(S::Squares, i::Int)
|
|||
|
1 <= i <= S.count || throw(BoundsError(S, i))
|
|||
|
return i*i
|
|||
|
end
|
|||
|
|
|||
|
julia> 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> Base.endof(S::Squares) = length(S)
|
|||
|
|
|||
|
julia> 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> Base.getindex(S::Squares, i::Number) = S[convert(Int, i)]
|
|||
|
|
|||
|
julia> Base.getindex(S::Squares, I) = [S[i] for i in I]
|
|||
|
|
|||
|
julia> 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'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'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
|
|||
|
count::Int
|
|||
|
end
|
|||
|
|
|||
|
julia> Base.size(S::SquaresVector) = (S.count,)
|
|||
|
|
|||
|
julia> Base.IndexStyle(::Type{<:SquaresVector}) = IndexLinear()
|
|||
|
|
|||
|
julia> Base.getindex(S::SquaresVector, i::Int) = i*i</code></pre><p>Note that it'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> s = SquaresVector(7)
|
|||
|
7-element SquaresVector:
|
|||
|
1
|
|||
|
4
|
|||
|
9
|
|||
|
16
|
|||
|
25
|
|||
|
36
|
|||
|
49
|
|||
|
|
|||
|
julia> s[s .> 20]
|
|||
|
3-element Array{Int64,1}:
|
|||
|
25
|
|||
|
36
|
|||
|
49
|
|||
|
|
|||
|
julia> 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> s ⋅ s # dot(s, s)
|
|||
|
4676</code></pre><p>As a more complicated example, let'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> struct SparseArray{T,N} <: AbstractArray{T,N}
|
|||
|
data::Dict{NTuple{N,Int}, T}
|
|||
|
dims::NTuple{N,Int}
|
|||
|
end
|
|||
|
|
|||
|
julia> SparseArray{T}(::Type{T}, dims::Int...) = SparseArray(T, dims);
|
|||
|
|
|||
|
julia> SparseArray{T,N}(::Type{T}, dims::NTuple{N,Int}) = SparseArray{T,N}(Dict{NTuple{N,Int}, T}(), dims);
|
|||
|
|
|||
|
julia> Base.size(A::SparseArray) = A.dims
|
|||
|
|
|||
|
julia> Base.similar(A::SparseArray, ::Type{T}, dims::Dims) where {T} = SparseArray(T, dims)
|
|||
|
|
|||
|
julia> Base.getindex(A::SparseArray{T,N}, I::Vararg{Int,N}) where {T,N} = get(A.data, I, zero(T))
|
|||
|
|
|||
|
julia> 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> 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> 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> 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> 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'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> 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> A[SquaresVector(3)]
|
|||
|
3-element SparseArray{Float64,1}:
|
|||
|
1.0
|
|||
|
4.0
|
|||
|
9.0
|
|||
|
|
|||
|
julia> 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>
|