Skip to content

Commit 2ab9d78

Browse files
committed
Implemented iteration interface for Poly
Implemented iteration interface returning terms of a given `Poly` object.
1 parent 85e2bcc commit 2ab9d78

File tree

2 files changed

+30
-12
lines changed

2 files changed

+30
-12
lines changed

src/Polynomials.jl

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ export degree, coeffs, variable
1212
export polyval, polyint, polyder, roots, polyfit
1313
export Pade, padeval
1414

15-
import Base: length, endof, getindex, setindex!, copy, zero, one, convert, norm, gcd
15+
import Base: start, next, done, length, size, eltype
16+
import Base: endof, getindex, setindex!, copy, zero, one, convert, norm, gcd
1617
import Base: show, print, *, /, //, -, +, ==, isapprox, divrem, div, rem, eltype
1718
import Base: promote_rule, truncate, chop, call, conj, transpose, dot, hash
1819
import Base: isequal
@@ -110,15 +111,26 @@ convert{T, S<:Number}(::Type{Poly{T}}, x::AbstractArray{S}, var::SymbolLike=:x)
110111
promote_rule{T, S}(::Type{Poly{T}}, ::Type{Poly{S}}) = Poly{promote_type(T, S)}
111112
promote_rule{T, S<:Number}(::Type{Poly{T}}, ::Type{S}) = Poly{promote_type(T, S)}
112113
eltype{T}(::Poly{T}) = T
113-
eltype{T}(::Type{Poly{T}}) = T
114114

115115
"""
116116
117-
`legnth(p::Poly)`: return length of coefficient vector
117+
`length(p::Poly)`: return length of coefficient vector
118118
119119
"""
120-
length(p::Poly) = length(p.a)
121-
endof(p::Poly) = length(p) - 1
120+
length(p::Poly) = length(coeffs(p))
121+
endof(p::Poly) = length(p) - 1
122+
123+
start(p::Poly) = start(coeffs(p)) - 1
124+
next(p::Poly, state) = (temp = zeros(coeffs(p)); temp[state+1] = p[state]; (Poly(temp), state+1))
125+
done(p::Poly, state) = state > degree(p)
126+
eltype{T}(::Type{Poly{T}}) = Poly{T}
127+
"""
128+
129+
`size(p::Poly)`: return size of coefficient vector
130+
131+
"""
132+
size(p::Poly) = size(p.a)
133+
size(p::Poly, i::Integer) = size(p.a, i)
122134

123135
"""
124136

test/runtests.jl

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -205,13 +205,6 @@ p2 = convert(Poly{Int64}, p1)
205205
p2[3] = 3
206206
@test p1[3] == 3
207207

208-
209-
## eltype of a Poly type
210-
types = [Int, UInt8, Float64]
211-
for t in types
212-
@test t == eltype(Poly{t})
213-
end
214-
215208
## Polynomials with non-Real type
216209
import Base: +, *, -
217210
immutable Mod2 <: Number
@@ -318,3 +311,16 @@ p2s = Poly([1], :s)
318311

319312
@test Poly([0.5]) + 2 == Poly([2.5])
320313
@test 2 - Poly([0.5]) == Poly([1.5])
314+
315+
# test size
316+
@test size(Poly([0.5, 0.2])) == (2,)
317+
@test size(Poly([0.5, 0.2]), 1) == 2
318+
@test size(Poly([0.5, 0.2]), 1, 2) == (2,1)
319+
320+
# test iteration
321+
p1 = Poly([1,2,0,3])
322+
for term in p1
323+
@test isa(term, Poly)
324+
end
325+
326+
@test eltype(typeof(p1)) == typeof(p1)

0 commit comments

Comments
 (0)