Nerdamer Scripting

Nerdamer Scripting Beta

Scripting lets the text you pass to nerdamer(...) do more than one thing: store values, define functions, make decisions and repeat steps. It runs inside Nerdamer, not as JavaScript.

import nerdamer from 'nerdamer';

// Notation: one expression

nerdamer('factor(x^2-1)');        // (1+x)*(-1+x)


// Scripting: define a function, then use it

nerdamer(`
square(x):=x^2;
square(6)
`);                               // 36

Variables

Assign with :.

a:5;
b:a+2;
b                        // 7
: and = are different. x:5 assigns 5 to x. x=5 is the equation x=5.

Store any result the same way, including solutions:

sol: solve(sin(x),x);
evaluate(sol,{_n=>0})    // {0}

_n stands for "any integer" in periodic solutions and can't be assigned (_n:0 is an error). The {_n=>0} above applies only to that evaluate call.

A value stays until you remove it, and later calls see it. Use unassign(a) to remove one, nerdamer.clearVars() from JavaScript to remove all, or let for a value that exists only inside one expression.

Statements

Separate statements with ;. A new line alone doesn't end a statement.

f(x):=x^2+1;
f(12)                    // 145

Inside one expression, block runs its arguments in order and returns the last one. let does the same with temporary values:

block(a:2, b:3, a+b)     // 5

let(x, 2, y, 3, x+y)     // 5

Your own functions

Define a function with f(x):=.... Functions can call themselves:

f(n):=if(n<2, 1, n*f(n-1));
f(5)                     // 120

You can also define them from JavaScript with nerdamer.setFunction(...). See User-defined functions for both.

Conditions

if evaluates only the branch it picks. Combine conditions with and, or, not and xor, which return 1 or 0.

x:-3;
if(x>0, x, -x)           // 3

and(x>-5, x<0)           // 1

Loops

while repeats while its condition is nonzero. for takes a start, a condition, a step and a body. each visits every element of a vector, matrix or set.

block(x:0, while(x<3, x:x+1), x)                              // 3

block(total:0, for(k:1, 5-k, k:k+1, total:total+k), total)    // 10

block(total:0, each([1,2,3], v, total:total+v), total)        // 6

break() leaves a loop, and continue() skips to its next pass.

block(x:0, while(1, block(x:x+1, if(x>4, break(), 0))), x)    // 5

Returning early

return ends a function or block with a value.

g(x):=block(if(x<0, return(0), 0), sqrt(x));
g(-4)                    // 0

g(9)                     // 3

Errors

iferror gives a fallback when an expression fails. iserror tells you whether it fails.

iferror(0/0, 7)          // 7

iserror(0/0)             // 1

Evaluating with values

evaluate computes a value now, optionally with values for the variables. The values apply to that call only.

evaluate([x+y, x*y], {x=>2, y=>3})   // [5, 6]

For longer programs, see the Scripting examples.

Reference