## Mathematica's own programming model: functions and expressions

There are many books on *Mathematica* programming, we still see a lot of people falling to understand *Mathematica*The programming model of and generally understand it badly as *functional programming*.

It's because we can pass a *a function* as an argument, as

```
plotZeroPi(f_) := Plot(f(x), {x,0,Pi});
plotZeroPi(Sin) (* produces Plot(Sin(x),{x,0,Pi}) *)
```

and so people tend to think that *Mathematica* follows a functional programming model (FP). There is even a section in the functional programming documentation. Yes, it looks like, but it's different – and you'll see why soon.

### Expressions are what the assessment is about

All in *Mathematica* is an expression. An expression can be an atom, such as numbers, symbol variables and other embedded atoms, or a compound expression. The compound expressions (our subject here) have a *head* followed by arguments in brackets, such as `Sin(x)`

.

Thus, the assessment in *Mathematica* is the transformation going from one expression to another based on some *rules*, defined by the user and integrated, until no rule is applicable. This last expression is returned as an answer.

*Mathematica* Its strength derives from this simple concept, to which many syntactic sugars are added to write expressions in a more concise manner … and we will see further below. We do not intend to explain all the details here, as there are other sections in this guide to help you.

In fact, what happened above is the definition of a new *head*, `plotZeroPi`

via the infix operator `:=`

. Moreover, the first argument is a *pattern expression* `plotZeroPi(f_)`

, with head (as a motif) `plotZeroPi`

and a reason argument. The notation `f_`

simply introduce a *all* pattern and give him a name, `f`

, which we use in the right side **as the head of another expression**.

That's why a common way to express this `f`

Is `plotZeroPi`

has a function argument – although it's not very accurate, and we also say that `plotZeroPi`

is a *a function* (or a high-level function in FP jargon), although it is now clear that there is a little abuse of terminology here.

Bottom line: *Mathematica* looks like functional programming because we are able to define and circumvent heads.

### Put the assessment on hold

But, note that `Plot`

do not expect a function, but an expression! Thus, although in a functional programming paradigm, one would write `Plot`

with a *a function* parameter, in *Mathematica* the plot is waiting for an expression. It was a design choice in *Mathematica* and the one I say makes it quite readable.

It works because `Plot`

is reported to *hold* the evaluation of its arguments (see nonstandard). Once `Plot`

defines its environment internally, it triggers the evaluation of the expression with specific values assigned to `x`

. When reading the documentation, beware of this subtlety: it says *a function* although a better term would have been *expression*.

### Dynamically create a head

So what happens if we have to perform a complex operation and once it's done, a function is clearly defined? Say you want to calculate `Sin(`

$ alpha $ `x)`

, where $ alpha $ is the result of a complex operation. A naive approach is

```
func(p_, x_) := Sin(costlyfunction(p) x)
```

If you try then

```
Plot(func(1.,x), {x,0,Pi})
```

you can wait a long time to get this plot. Even that does not work

```
func(p_)(x_) := Sin(costlyfunction(p) x)
```

because the entire expression is not evaluated by entering `Plot`

anyway. In fact, if you try func (1.) In the front-end, you will see that *Mathematica* knows no rules about it and can not do much either.

What you need is something that allows you to return a **head** of an expression. This thing will have `costlyfunction`

calculated once before `Plot`

take your head (the expression, not yours) and give him a `x`

.

*Mathematica* has an integrated, `Function`

it gives you that.

```
func(p_) := With({a = costlyfunction(p)}, Function(x, Sin(a x)) );
```

`With`

introduces a new context where this costly function is evaluated and attributed to `a`

. This value is recalled by `Function`

as it appears as a local symbol in its definition. `Function`

nothing is more than one *head* that you can use when needed. For those who are familiar with functional programming in other languages, `a`

is part of the *closing* where the `Function`

is defined; and `Function`

is the way we enter a *lambda* build in *Mathematica*.

Another way to do it, more imperative if you like, use `Module`

and what you already know about setting rules (which are more familiar with procedural programming):

```
func(p_) := Module({f, a},
a = costlyfunction(p);
f(x_) := Sin(a x);
f
);
```

In this document, a new context is introduced with two symbols, `f`

and `a`

; and what he does is simple: he calculates `a`

, then defines `f`

like a **head** as we want, and finally returns this symbol `f`

as answer, a newly created head that you can use in the caller.

In this definition, when you try to say, func (1.), you'll see a fun symbol like `f$3600`

to be returned. That's the symbol that has the rule `f(x_) := Sin(a x)`

attached to her. It was created by `Module`

to isolate any potential use of `f`

of the outside world. It works, but it's certainly not as idiomatic as `function`

.

The approach with `Function`

is more direct, and there is syntactic sugar for that too; you will see it regularly *Mathematica* programming

```
func(p_) := With({a = costlyfunction(p)}, Sin(a #)& );
```

Ok, let's continue.

Now that `func`

really returns a *a function*, that is to say something that you can use as an expression head. You would use it with `Plot`

as

```
With({f = func(1.)}, Plot(f(x),{x,0,Pi}))
```

and we bet that & # 39; at that time you will understand why `Plot(func(1.)(x),{x,0,Pi})`

is as bad as any of the previous examples.

### Returning an expression

A final example is `Piecewise`

(documentation)

```
Plot(Piecewise({{x^2, x < 0}, {x, x > 0}}), {x, -2, 2})
```

So what will happen if the limit condition is a parameter? Well, just apply the recipe above:

```
paramPieces(p_) := Piecewise({{#^2, # < p}, {#, # > p}}) &;
```

Do not do

```
paramPieces(p_) := Piecewise({{x^2, x < p}, {x, x > p}});
```

because `Piecewise`

does not have the *hold* attribute and he will try to evaluate his argument. He does not expect an expression! Yes `x`

is not defined, you can see a nice exit when you use it, but now you are forced to use the atom (variable name) `x`

well

```
Plot(paramPieces(0), {x, -1, 1})
```

seems to work, you're getting ready to get into trouble. So, how to return something that you can use in `Plot`

?

Well, in this case, the parameter is not a load for the calculation itself, so we see what kind of definitions are used

```
paramPieces(p_, x_) := Piecewise({{x^2, x < p}, {x, x > p}});
Plot(paramPieces(0, x), {x,-1,1})
```

And if x is not defined, `paramPieces(0, x)`

is nicely displayed in the front-end as before. It works because, again, *Mathematica* is a *language of expressions*and the parameter `x`

makes as much sense as the number `1.23`

in the definition of `paramPieces`

. As told, *Mathematica* just stop the assessment of `paramPieces(0, x)`

when no more rules are applied.

### A note on the mission

We have said above several times that `x`

is given a value on the inside `Plot`

etc. Again, beware, this is not the same thing as variable assignment in functional programming and there are (still) misnomer for the sake of clarity.

What's in it? *Mathematica* is a new rule that allows the evaluation loop to replace all occurrences of `x`

by a value. As an aperitif, the following works

```
Plot3D(Sin(x(1) + x(2)), {x(1), -Pi, Pi}, {x(2), -Pi, Pi})
```

There is no *variable* `x(1)`

, just an expression that incorporates one or more new rules `Plot`

each time & # 39; obtains a value for tracing. You can find out more about this in this guide as well.

**Note to readers:** Although these guides are not intended to be exhaustive, do not hesitate to leave comments to improve them.