Top and leaves of an expression

### 8.2.3 Top and leaves of an expression

An expression can be represented by a tree. The top of the tree is either an operator or a function and the leaves of the tree are the arguments of the operator or function (see also Section 6.1.10).

The sommet command finds the top of an expression.

- sommet takes expr, an expression.
- sommet(expr) returns the top of expr.

#### Examples

sommet(sin(x+2))

sin |  |  |  |  |  |  |  |  |  |

sommet(x+2*y)

+ |  |  |  |  |  |  |  |  |  |

The op or feuille command finds the list of the leaves of an expression.

- op takes expr, an expression.
- op(expr) returns the leaves of expr.

#### Examples

op(sin(x+2))

or:

feuille(sin(x+2))

x+2 |  |  |  |  |  |  |  |  |  |

op(x+2*y)

or:

feuille(x+2*y)

x,2 y |  |  |  |  |  |  |  |  |  |

If the top of an expression expr is an infixed operator, the left hand side will be expr[1] and the right hand side will be expr[2]. The left and right commands are alternative commands to find the sides (see Section 5.2.4, Section 6.5.1, Section 6.6.2, Section 6.3.6, Section 9.3.4 and Section 9.3.5 for other uses of left and right.)

- left and right take one argument: expr, an expression whose top is an infixed operator.
- left(expr) returns the left side of the operator.
- right(expr) returns the right side of the operator.

#### Examples

sommet(y=x^2)

= |  |  |  |  |  |  |  |  |  |

left(y=x^2)

y |  |  |  |  |  |  |  |  |  |

right(y=x^2)

x2 |  |  |  |  |  |  |  |  |  |

##### Remark.

If a function is defined by a program (see Section 25.1.2) then the top will be the function ’program’ and the leaves will be a sequence consisting of the arguments of the defined function, followed by a sequence of 0s (one for each argument) followed by the body of the function. For example, define the pgcd function:

pgcd(a,b):={ local r; while (b!=0) { r:=irem(a,b); a:=b; b:=r; } return a; }

Then:

sommet(pgcd)

program |  |  |  |  |  |  |  |  |  |

feuille(pgcd)[0]

or:

op(pgcd)[0]

a,b |  |  |  |  |  |  |  |  |  |

feuille(pgcd)[1]

or:

op(pgcd)[1]

0,0 |  |  |  |  |  |  |  |  |  |

feuille(pgcd)[2]

or:

op(pgcd)[2]

{ local r; while(b<>0) { r:=irem(a,b); a:=b; b:=r; } return a; }