From 1233ad4269ac657a003b6c63d1b6c0409770d284 Mon Sep 17 00:00:00 2001 From: PaddiM8 Date: Sun, 13 Dec 2020 17:45:06 +0100 Subject: [PATCH] Optimised 'sum' function --- kalk/src/interpreter.rs | 16 +++++++++------- kalk/src/kalk_num.rs | 6 ++++++ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/kalk/src/interpreter.rs b/kalk/src/interpreter.rs index 8ff39b8..1929beb 100644 --- a/kalk/src/interpreter.rs +++ b/kalk/src/interpreter.rs @@ -11,6 +11,7 @@ pub struct Context<'a> { symbol_table: &'a mut SymbolTable, angle_unit: String, precision: u32, + sum_n_value: Option, } impl<'a> Context<'a> { @@ -19,6 +20,7 @@ impl<'a> Context<'a> { angle_unit: angle_unit.into(), symbol_table, precision, + sum_n_value: None, } } @@ -203,6 +205,12 @@ fn eval_var_expr( return eval_expr(context, &Expr::Literal(*value), unit); } + if identifier == "n" { + if let Some(value) = context.sum_n_value { + return Ok(KalkNum::from(value)); + } + } + // Look for the variable in the symbol table let var_decl = context.symbol_table.get_var(identifier).cloned(); match var_decl { @@ -266,13 +274,7 @@ fn eval_fn_call_expr( let mut sum = Float::with_val(context.precision, 0); for n in start..=end { - let n_expr = Expr::Literal(n as f64); - - // Update the variable "n" in the symbol table on every iteration, - // then calculate the expression and add it to the total sum. - context - .symbol_table - .set(Stmt::VarDecl(String::from("n"), Box::new(n_expr))); + context.sum_n_value = Some(n); sum += eval_expr(context, &expressions[2], "")?.value; } diff --git a/kalk/src/kalk_num.rs b/kalk/src/kalk_num.rs index d4725cc..320332d 100644 --- a/kalk/src/kalk_num.rs +++ b/kalk/src/kalk_num.rs @@ -180,6 +180,12 @@ impl From for KalkNum { } } +impl From for KalkNum { + fn from(x: i128) -> Self { + KalkNum::new(Float::with_val(63, x), "") + } +} + impl From for KalkNum { fn from(x: i64) -> Self { KalkNum::new(Float::with_val(63, x), "")