# compile() Function & Examples

Use the compile() expression function in Calcul.io. Review its syntax, edit working examples, understand the result, and explore related math functions.

## compile

#### compile(expr)

#### compile([expr1, expr2, expr3, ...])

Try it yourself:

```calculio
code1 = compile("sqrt(3^2 + 4^2)")
code1.evaluate()
code2 = compile("a * b")
code2.evaluate({a: 3, b: 4})
```

[parser](https://calcul.io/function/parser/index.md)

[parse](https://calcul.io/function/parse/index.md)

---

## Compile expressions for repeated calculation

**compile(expr)** turns a parsed mathematical expression into an object that can be evaluated repeatedly. It is useful when an expression is fixed but its variables change: compile once, then provide a different scope for each calculation. This avoids repeatedly parsing text and keeps application code clear.

## How compilation fits the workflow

Start with an expression such as `x^2 + 2*x + 1`, compile it, and evaluate it with a scope where `x` has a value. For a single, direct calculation, [evaluate](https://calcul.io/function/evaluate/index.md) is usually simpler. Use [parse](https://calcul.io/function/parse/index.md) when you need to inspect or transform the expression tree first, and [simplify](https://calcul.io/function/simplify/index.md) when a reduced symbolic form is helpful.

## Practical example

A pricing rule can be compiled once and evaluated for many orders: `subtotal * (1 - discount) + shipping`. Supplying a fresh scope for each order is preferable to changing global variables. The same pattern works for simulations, plotted functions, and reusable formulas. If a formula contains constants such as `pi`, they can normally be resolved along with values in the supplied scope.

## Inputs and safe use

The expression must use valid calculator syntax. Compilation does not make an invalid expression valid; syntax errors should be handled before evaluation. Treat expressions received from users as code-like input: only expose the names and functions you intend to allow, and do not blindly evaluate untrusted formulas in a sensitive environment. For symbolic tasks, pair compilation with [derivative](https://calcul.io/function/derivative/index.md) or [integrate](https://calcul.io/function/integrate/index.md); use [resolve](https://calcul.io/function/resolve/index.md) when names in an expression need to be examined.

## When to choose another function

Use [evaluate](https://calcul.io/function/evaluate/index.md) for an ad-hoc answer, and compilation when the expression will be run again. Keeping those two jobs distinct makes formulas easier to test and reuse.

[All functions](https://calcul.io/functions/index.md)
