Creating a struct with symbolic (Symbolics package) functions and variables

I am trying to write a struct with members to manipulate symbolic variables. I am a newbie to Julia. I have programmed in python using sympy for symbolic algebra. Here is the code I have so far -

using Symbolics, SymbolicUtils

mutable struct SYMBOLS
    num_vars::Int
    latex_map::Dict
    vars::Vector{SymbolicUtils.Sym{Real}}
    add
    latex
    dump
end

function Symbols_add(s::String)
    syms = split(s," ")
    n = length(syms)
    for i in 1:n
        Symbols.latex_map[Symbols.vars[i]] = syms[i+Symbols.num_vars]
    end
    Symbols.num_vars = Symbols.num_vars+n
    return Symbols.var[Symbols.num_vars:Symbols.num_vars-n]
end

function Symbols_latex(sym::SymbolicUtils.Sym{Real})
    return Symbols.latex_map(sym)
end

function Symbols_dump()
    for s in Symbols.var_lst
        println(Symbols.latex_map[s])
    end
end

Symbols = SYMBOLS(0,Dict(),@variables X[1:50],Symbols_add,Symbols_latex,Symbols_dump)

(x,y,z) = Symbols.add("x y z")
(a,b) = Symbols.add(raw"\alpha \beta")

Symbols.dump()

and this is my error message -

ERROR: LoadError: invalid redefinition of constant Symbols_add
Stacktrace:
[1] top-level scope
@ ~/MyJulia/MySymbols.jl:32
in expression starting at /home/brombo/MyJulia/MySymbols.jl:32

I feel that I must be declaring the types of the members of the SYMBOLS struct or the the types of the functions I entered into the SYMBOLS constructor incorrectly but can find no examples of how to do it correctly. Documentation of struct with members that a functions that are not one-line functions seems to be almost non-existent. Any suggestions would be appreciated.

Never used Symbolics before, but the expression @variables X[1:50], Symbols_add, Symbols_latex, Symbols_dump is making the macro operate on a tuple of all those, and it’s erroring at trying to reassign the implicitly const function name Symbols_add. It’s covered in the docs but doesn’t cover implicit tuple parentheses, so here’s an example:

julia> macro id(args...) args end
@id (macro with 1 method)

julia> @id 1 2 3 # typical one-liner, 3 Ints
(1, 2, 3)

julia> @id(1, 2, 3) # equivalent call expression
(1, 2, 3)

julia> @id (1, 2, 3) # spacing does one-liner, now 1 tuple
(:((1, 2, 3)),)

julia> @id 1, 2, 3 # still 1 tuple argument
(:((1, 2, 3)),)

To fix the macro call, you would just change to @variables(X[1:50]) or (@variables X[1:50]). But I’m not sure it wouldn’t cause another error, could give it a try.

Thanks for you efforts. By suggestions did cause a whole slew of new errors. I think I need help from someone familiar with the Symbolics package.

This is of course unrelated and fixed by not having a non-function version of that.

They are all just Num{SymbolicUtils.BasicSymbolic}

Thank you that worked. Sometimes the simplest things are the hardest to see!

1 Like