Skip to content

Commit

Permalink
example in readme changed. todo update
Browse files Browse the repository at this point in the history
  • Loading branch information
Alessandro committed Sep 10, 2021
1 parent 41986a9 commit f3a0dfe
Showing 1 changed file with 1 addition and 57 deletions.
58 changes: 1 addition & 57 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,60 +69,4 @@ Define this for your symbolic types if you want `SymbolicUtils.simplify` to appl
specific to numbers (such as commutativity of multiplication). Or such
rules that may be implemented in the future.

## Example

Suppose you were feeling the temptations of type piracy and wanted to make a quick and dirty
symbolic library built on top of Julia's `Expr` type, e.g.

```julia
for f [:+, :-, :*, :/, :^] #Note, this is type piracy!
@eval begin
Base.$f(x::Union{Expr, Symbol}, y::Number) = Expr(:call, $f, x, y)
Base.$f(x::Number, y::Union{Expr, Symbol}) = Expr(:call, $f, x, y)
Base.$f(x::Union{Expr, Symbol}, y::Union{Expr, Symbol}) = (Expr(:call, $f, x, y))
end
end

Base.zero(t::Expr) = 0

ex = 1 + (:x - 2)
```


How can we use SymbolicUtils.jl to convert `ex` to `(-)(:x, 1)`? We simply implement `istree`,
`head`, `arguments` and we'll be able to do rule-based rewriting on `Expr`s:
```julia
using TermInterface
using SymbolicUtils


TermInterface.istree(ex::Expr) = ex.head == :call
TermInterface.operation(ex::Expr) = ex.args[1]
TermInterface.arguments(ex::Expr) = ex.args[2:end]
TermInterface.similarterm(x::Type{Expr}, head, args, symtype=nothing; metadata=nothing) =
Expr(:call, head, args...)

TermInterface.issym(s::Symbol) = true
Base.nameof(s::Symbol) = s

@rule(~x => ~x - 1)(ex)
```

However, this is not enough to get SymbolicUtils to use its own algebraic simplification system on `Expr`s:
```julia
simplify(ex)
```

The reason that the expression was not simplified is that the expression tree is untyped, so SymbolicUtils
doesn't know what rules to apply to the expression. To mimic the behaviour of most computer algebra
systems, the simplest thing to do would be to assume that all `Expr`s are of type `Number`:

```julia
Base.zero(t::Expr) = 0
TermInterface.symtype(::Expr) = Real
TermInterface.symtype(::Symbol) = Real

simplify(ex)
```

Now SymbolicUtils is able to apply the `Number` simplification rule to `Expr`.
<!-- TODO update examples -->

0 comments on commit f3a0dfe

Please sign in to comment.