pub fn execute_string(
code: &str,
interp: &mut Interpreter,
) -> Result<(), RuntimeError>Examples found in repository?
examples/simple_calculator.rs (line 26)
8fn main() {
9 // Create a new interpreter instance
10 let mut interp = Interpreter::new();
11
12 // Define some calculations to perform
13 let expressions = vec![
14 ("5 3 +", "Addition"),
15 ("10 4 -", "Subtraction"),
16 ("7 6 *", "Multiplication"),
17 ("20 4 /", "Division"),
18 ("3 dup *", "3 squared (3 * 3)"),
19 ("[1 2 3 4 5] length", "List length"),
20 ];
21
22 println!("Uni Calculator Example\n");
23
24 for (expr, description) in expressions {
25 // Execute the expression
26 match execute_string(expr, &mut interp) {
27 Ok(()) => {
28 // Get the result from the stack
29 if let Some(result) = interp.stack.last() {
30 println!("{}: {} = {}", description, expr, result);
31 }
32 }
33 Err(e) => {
34 eprintln!("Error evaluating '{}': {:?}", expr, e);
35 }
36 }
37
38 // Clear the stack for next calculation
39 interp.stack.clear();
40 }
41
42 println!("\nDefining and using a custom function:");
43
44 // Define a square function and use it
45 match execute_string("'square [dup *] def 5 square", &mut interp) {
46 Ok(()) => {
47 if let Some(result) = interp.stack.last() {
48 println!("5 squared = {}", result);
49 }
50 }
51 Err(e) => {
52 eprintln!("Error: {:?}", e);
53 }
54 }
55}