3

Situation

I use Last to extract the last element of an expression. Let poly=a+b*c+Log[a]+z.

Problem

When Using Last@poly, I expect the output is z. However, the command gave me Log[a].

Debug

With FullForm@poly, I found the output is Plus[a,Times[b,c],z,Log[a]]. So, Log[a] should be the correct answer of the command, but not my expected answer.

My Question

The strange behavior confuse me.

  1. I wonder whether elements of an expression in mathematica have definite order.
  2. If the answer is "no", is there any alternative other than Last to avoid the undetermined behavior, so that I can extract particular element ?
PureLine
  • 1,310
  • 7
  • 20
  • 1
    Plus[] is commutative, so it has the Orderless attribute, and sorts its arguments into a canonical order. Anyway: Defer[a + b c + Log[a] + z][[1, -1]]. Not recommended, though. – J. M.'s missing motivation Nov 07 '15 at 09:54
  • Take a look at the output of poly = .... The last element is indeed Log[a] because Mathematica sorts the terms of Plus. Why? Check here: http://reference.wolfram.com/language/ref/Orderless.html http://reference.wolfram.com/language/tutorial/FlatAndOrderlessFunctions.html – Szabolcs Nov 07 '15 at 09:55

1 Answers1

6

I wonder whether elements of an expression in mathematica have definite order.

Yes, the one you get after evaluating an expression. See Polynomial Ordering in the Wolfram Documentation Center. In your case, poly = a + b*c + Log[a] + z evaluates to

a + b c + z + Log[a]

So Last does indeed do what it's supposed to.

You could try extracting the elements with patterns (depending on what terms you actually need to extract), or you could use something like PolynomialForm[%,TraditionalOrder->True] (found here).

Some general information about term ordering in Mathematica

Functions in Mathematica can have the Orderless attribute, which means that Mathematica will (re)arrange the supplied terms in canonical order, as described in this tutorial. Canonical ordering is used as a standard way to arrange terms in commutative and associative functions (such as Plus or Times in your case) for purposes of for example pattern matching.

Graumagier
  • 1,130
  • 5
  • 11