1 |
|
2 |
|
3 | # Function parser
|
4 |
|
5 | Create a parser. The function creates a new `math.Parser` object.
|
6 |
|
7 |
|
8 | ## Syntax
|
9 |
|
10 | ```js
|
11 | math.parser()
|
12 | ```
|
13 |
|
14 | ### Parameters
|
15 |
|
16 | Parameter | Type | Description
|
17 | --------- | ---- | -----------
|
18 |
|
19 |
|
20 | ### Returns
|
21 |
|
22 | Type | Description
|
23 | ---- | -----------
|
24 | Parser | Parser
|
25 |
|
26 |
|
27 | ## Examples
|
28 |
|
29 | ```js
|
30 | const parser = new math.parser()
|
31 |
|
32 | // evaluate expressions
|
33 | const a = parser.evaluate('sqrt(3^2 + 4^2)') // 5
|
34 | const b = parser.evaluate('sqrt(-4)') // 2i
|
35 | const c = parser.evaluate('2 inch in cm') // 5.08 cm
|
36 | const d = parser.evaluate('cos(45 deg)') // 0.7071067811865476
|
37 |
|
38 | // define variables and functions
|
39 | parser.evaluate('x = 7 / 2') // 3.5
|
40 | parser.evaluate('x + 3') // 6.5
|
41 | parser.evaluate('function f(x, y) = x^y') // f(x, y)
|
42 | parser.evaluate('f(2, 3)') // 8
|
43 |
|
44 | // get and set variables and functions
|
45 | const x = parser.get('x') // 7
|
46 | const f = parser.get('f') // function
|
47 | const g = f(3, 2) // 9
|
48 | parser.set('h', 500)
|
49 | const i = parser.evaluate('h / 2') // 250
|
50 | parser.set('hello', function (name) {
|
51 | return 'hello, ' + name + '!'
|
52 | })
|
53 | parser.evaluate('hello("user")') // "hello, user!"
|
54 |
|
55 | // clear defined functions and variables
|
56 | parser.clear()
|
57 | ```
|
58 |
|
59 |
|
60 | ## See also
|
61 |
|
62 | [evaluate](evaluate.md),
|
63 | [compile](compile.md),
|
64 | [parse](parse.md)
|