# Symbolics.jl rewrite rule

**URL:** <https://discourse.julialang.org/t/symbolics-jl-rewrite-rule/105041>\
**Category:** General Usage\
**Tags:** symbolics\
**Created:** [October 17, 2023, 1:11am UTC](https://discourse.julialang.org/t/symbolics-jl-rewrite-rule/105041 "2023-10-17T01:11:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ian\_L](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ian_l/32/49509_2.png) [@Ian\_L](https://discourse.julialang.org/u/Ian_L)\
**Post date:** [October 17, 2023, 1:11am UTC](https://discourse.julialang.org/t/symbolics-jl-rewrite-rule/105041/1 "2023-10-17T01:11:25Z")

</div>

I defined the following rule:

```julia
rlogexp = @rule log(exp(~x)) => ~x

```

This seems to work for simple expressions:

```julia
> simplify(log(exp(x+3)), rewriter=rlogexp) 
3+x

```

However, this doesn’t seem to simplify

```julia
> simplify(log(exp(x))+3, rewriter=rlogexp)
log(exp(x))+3

```

What am I doing wrong?

---

<div class="post-metadata">

**Author:** ![Baptiste\_Lamic](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baptiste_lamic/32/202511_2.png) [@Baptiste\_Lamic](https://discourse.julialang.org/u/Baptiste_Lamic)\
**Post date:** [October 17, 2023, 2:21pm UTC](https://discourse.julialang.org/t/symbolics-jl-rewrite-rule/105041/2 "2023-10-17T14:21:25Z")

</div>

Hi, in the example you provided, the `simplify` function attempts to apply the rule once to the entire expression. If the entire expression doesn’t match the rule, it won’t be simplified.

To apply the rule from the bottom of the expression to the top, you can use the SymbolicUtils package and construct a custom rewriter. For instance:

```julia
using Symbolics
using SymbolicUtils.Rewriters

# Define the rule
rlogexp = @rule log(exp(~x)) => ~x

# Create a rewriter chain and use Postwalk
rewriter = [rlogexp] |> Chain |> Postwalk

@variables x

# Apply the rewriter to the expression
simplified_expr = simplify(log(exp(x)) + 3, rewriter)

```

The output is

> 3 + x

---

<div class="post-metadata">

**Author:** ![erny123](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/erny123/32/52255_2.png) [@erny123](https://discourse.julialang.org/u/erny123)\
**Post date:** [November 26, 2024, 10:55pm UTC](https://discourse.julialang.org/t/symbolics-jl-rewrite-rule/105041/3 "2024-11-26T22:55:38Z")

</div>

I don’t think this answer is helpful.

For example, if I have something like:

```julia
@variables x t Tinv(..) 

expr = Tinv(x)

trule = @rule Tinv(~z) => (~z)/2

simplify(expr, rewriter=trule) #doesn't simplify or apply rule

# Create a rewriter chain and use Postwalk
rewriter = [trule] |> Chain |> Postwalk

simplify(expr, rewriter) #doesn't simplify or apply rule

```
