0
$\begingroup$

The series

  • The series is: $\text{expr}_{1} \pm \text{expr}_{2} ...$
  • $\pm$ represents plus or minus sign.
  • The number of terms in the series can be 1 or more than 1.
  • Each term $\text{expr}_{n}$ is an expression, and not necessarily $ax^{n}$

Use Case

  • I want to transform the series by:
    • Writing a rule that split the series into 1st and remaining terms.
    • Writing another rule that transform the first term.
    • Using the two rule to transform all terms of the series.

Current Goal

  • I want to split the series into:

    • the first term, and
    • the remaining terms

Constraint

  • I only want the pattern to match for once.
    • There are several ways to split the expression into 2 parts
    • I only want a split that keeps the first term as simple as possible.

Test

I will use polynomials as test cases.

rule[expr_] = expr /. {Shortest[a_] + b__ :> a}

test1 = x - 2x^{2} + 3x^{3};
rule[test1]

test2 = -x^{4} + 2x^{2} + 3x^{3};
rule[test2]

test3 = -x;
rule[test3]

test4 := -2 x^3 + Sum[Log[x], {n, 1, L}]

Expected Result

  • $x$
  • $-x^{4}$
  • $-x$
  • $-2x^3$

Actual Result

  • $x - 2 x^2 + 3 x^3$

  • $2 x^2 + 3 x^3 - x^4$

  • $-x$

  • $L \log (x)-2 x^3$

Question

The rule matches with the whole series instead of the shortest first term.

How to fix the rule?

Thanks.

$\endgroup$
1
$\begingroup$

First of all, don't use braces around exponents.

Second,

SetAttributes[rule, HoldAll];
rule[exp_] := ({HoldForm[exp] /. Plus -> Sequence})[[1, 1]];
rule[x - 2 x^2 + 3 x^3]
rule[-x^4 + 2 x^2 + 3 x^3]
rule[-x]
(*
   x
   -x^4
   -x
*)
$\endgroup$
  • $\begingroup$ Pro: can extract each of all terms. Even works for things like: rule[Sum[Log[x], {n, 1, L}] - 2 x^{3}] Con: Doesnt work if I assign the expression to a variable first. For example, test = Sum[Log[x], {n, 1, L}] - 2 x^{3}; rule[test] yields $\left\{-2 x^3,L \log (x)\right\}$. $\endgroup$ – R zu Nov 21 '18 at 16:18
  • $\begingroup$ Since I am using this as part of a simplification, I don't need HoldForm. For my case, r1[exp_] := Part[{exp /. Plus -> Sequence}, 1]; works. $\endgroup$ – R zu Nov 21 '18 at 22:17
  • $\begingroup$ Problem: the function splits $\sum a + b$ to $\sum a$ and $b$, instead of $\sum a$ and $\sum b$. $\endgroup$ – R zu Nov 21 '18 at 22:51
0
$\begingroup$

Recursively apply rule to each term.

f[exp_] := exp //. {Plus[x1_, x2__] :> f[x1] + f[x2]}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.