Skip to content

Instantly share code, notes, and snippets.

@vtjnash
Created September 9, 2014 23:58
Show Gist options
  • Save vtjnash/1012bf9fbf58124c46fe to your computer and use it in GitHub Desktop.
Save vtjnash/1012bf9fbf58124c46fe to your computer and use it in GitHub Desktop.
# BEFORE:
function PolynomialRing{T <: Ring}(::Type{T}, s::String)
S = symbol(s)
T1 = Poly{T, S}
T2 = T
# Conversions and promotions
eval(:(Base.convert(::Type{$T1}, x::$T) = Poly($T1, [x])))
eval(:(Base.promote_rule(::Type{$T1}, ::Type{$T}) = $T1))
P = T2.parameters
while length(P) > 0
T2 = P[1]
if isa(T2, DataType) && T2 <: Ring
eval(:(Base.convert(::Type{$T1}, x::$T2) = Poly($T1, [convert($T, x)])))
eval(:(Base.promote_rule(::Type{$T1}, ::Type{$T2}) = $T1))
P = T2.parameters
else
break
end
end
if T != ZZ
eval(:(Base.convert(::Type{$T1}, x::ZZ) = Poly($T1, [convert($T, x)])))
eval(:(Base.promote_rule(::Type{$T1}, ::Type{ZZ}) = $T1))
end
eval(:(Base.convert(::Type{$T1}, x::Integer) = Poly($T1, [convert($T, x)])))
eval(:(Base.promote_rule{R <: Integer}(::Type{$T1}, ::Type{R}) = $T1))
# (Type, gen)
return (Poly{T, S}, Poly(Poly{T, S}, [T(0), T(1)]))
end
-----------
#AFTER:
Base.eltype{T}(::Type{Poly{T}}) = T
Base.convert{T<:Ring, S}(::Type{Poly{T,S}}, x::Ring) = Poly{T,S}([convert(T,x)])
Base.promote_rule{T1<:Poly, T<:Ring}(::Type{T1}, ::Type{T}) = T1
Base.convert{T1<:Poly}(::Type{T1}, x::Integer) = Poly(T1, [convert(eltype(T1), x)])
Base.promote_rule{T1<:Poly, R <: Integer}(::Type{T1}, ::Type{R}) = T1
PolynomialRing{T <: Ring}(::Type{T}, s::String) = PolynomialRing(T, symbol(s))
function PolynomialRing{T <: Ring}(::Type{T}, S::Symbol)
return (Poly{T, S}, Poly(Poly{T, S}, [T(0), T(1)]))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment