Alternatively and without any need for trickery:

julia> using Polynomial

julia> x=Poly([1,0],:x)
Poly(x)

julia> 2x^2 + 1
Poly(2x^2 + 1)


On Thu, Mar 6, 2014 at 8:53 PM, andrew cooke <and...@acooke.org> wrote:

> ...possibly offensive to some.
>
> i wanted a nice syntax for people to define polynomials.  the code below
> lets you write things like
>
> 2X^2 + 3X + 1
> X+1
>
>
>
> and packages the coefficients into a nice format for a constructor (an
> array of (coeff, power)).
>
> this kind of thing is common in haskell where because of the lovely syntax
> you can "hide" function application in expressions.  i haven't seen
> anything similar in julia, but i haven;t read a lot of julia code.
>
> type Terms{I<:Integer}
>     terms::Array{(I, Int)}
> end
>
> type Power
>     exp::Int
> end
>
> type X end
>
> +{I<:Integer}(p1::Terms{I}, p2::Terms{I}) = Terms{I}(vcat(p1.terms, p2.
> terms))
> +{I<:Integer}(::Type{X}, p2::Terms{I}) = Terms{I}(vcat([(one(I),1)], p2.
> terms))
> +{I<:Integer}(p1::Terms{I}, ::Type{X}) = Terms{I}(vcat(p1.terms, [(one(I),
> 1)]))
> +{I<:Integer}(p1::Power, p2::Terms{I}) = Terms{I}(vcat([(one(I),p1.exp)],p2
> .te\
> rms))
> +{I<:Integer}(p1::Terms{I}, p2::Power) = Terms{I}(vcat(p1.terms, [(one(I),
> p2.ex\
> p)]))
> +{I<:Integer}(n::I, p2::Terms{I}) = Terms{I}(vcat([(n,0)], p2.terms))
> +{I<:Integer}(p1::Terms{I}, n::I) = Terms{I}(vcat(p1.terms, [(n,0)]))
>
> +{I<:Integer}(n::I, ::Type{X}) = Terms{I}([(n, 0),(one(I),1)])
> +{I<:Integer}(::Type{X}, n::I) = Terms{I}([(one(I),1), (n, 0)])
>
> ^(::Type{X}, exp::Int) = Power(exp)
> *{I<:Integer}(n::I, ::Type{X}) = Terms{I}([(n,1)])
> *{I<:Integer}(n::I, p::Power) = Terms{I}([(n,p.exp)])
>
> println(2X^2 + 3X + 1)
> println(X+1)
>
> which prints:
>
> Terms{Int64}([(2,2),(3,1),(1,0)])
> Terms{Int64}([(1,1),(1,0)])
>
> there are some issues.  X alone, for example, doesn't have enough info to
> define the subtype of Integer, which i need.  defining additional methods
> for that case to give a nice "syntax error" resulted in an explosion of
> ambiguous methods, so i dropped it an will try again later.
>
> also, you might hope to use promotion to avoid defining so much, but it
> turns out to be harder than i thought.
>
> anyway, i thought someone might find it amusing,
> andrew
>
>

Reply via email to