From a3ec0a57f85203742024316e255aede0b1f4f881 Mon Sep 17 00:00:00 2001 From: Laifsyn <99366187+Laifsyn@users.noreply.github.com> Date: Wed, 5 Jun 2024 07:32:20 -0500 Subject: [PATCH] =?UTF-8?q?Usar=20Tailcall=20Implementar=20versi=C3=B3n=20?= =?UTF-8?q?con=20tailcall=20para=20evitar=20stackoverflow=20en=20entradas?= =?UTF-8?q?=20relativamente=20grandes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/utp/clsEstructuraDatos/Cargo.toml | 4 ++++ .../laboratorio_2_rust/main.rs | 21 ++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/utp/clsEstructuraDatos/Cargo.toml b/src/main/java/com/utp/clsEstructuraDatos/Cargo.toml index c91bc9b..5803888 100644 --- a/src/main/java/com/utp/clsEstructuraDatos/Cargo.toml +++ b/src/main/java/com/utp/clsEstructuraDatos/Cargo.toml @@ -13,3 +13,7 @@ path = "laboratorio_2_rust/main.rs" colored = "2.1.0" inquire = "0.7.5" num-bigint = "0.4.5" +tailcall = "1.0.1" + +[features] +tailcall = [] diff --git a/src/main/java/com/utp/clsEstructuraDatos/laboratorio_2_rust/main.rs b/src/main/java/com/utp/clsEstructuraDatos/laboratorio_2_rust/main.rs index 2eeba6f..46ae014 100644 --- a/src/main/java/com/utp/clsEstructuraDatos/laboratorio_2_rust/main.rs +++ b/src/main/java/com/utp/clsEstructuraDatos/laboratorio_2_rust/main.rs @@ -59,6 +59,7 @@ fn spawn_app() { } }; }; + // Ejecutar la función seleccionada #[rustfmt::skip] match funcion { @@ -76,7 +77,7 @@ fn spawn_app() { println!("{}", format!("Factorial({}) no es calculable", args[0]).bright_red().bold()); continue; }; - println!("Factorial({}) = {factorial} ({} digitos)", args[0], factorial.to_string().len()); + println!("Factorial({}) = {factorial} \n{}", args[0], format!("({} digitos)", factorial.to_string().len()).on_black().cyan()); }, }; match Confirm::new("Desea salir?").with_placeholder("Y/N").prompt() { @@ -168,6 +169,7 @@ fn fib(nth: usize) -> Option { } /// Factorial Recursivo +#[cfg(not(feature = "tailcall"))] fn factorial(n: usize) -> Option { if let 0..=1 = n { return Some(1.into()); @@ -176,6 +178,23 @@ fn factorial(n: usize) -> Option { } } +/// Factorial Recursivo +/// Compilar con `tailcall` para obtener esta función +/// `cargo run --release --features "tailcall"` +#[cfg(feature = "tailcall")] +fn factorial>(n: T) -> Option { + use num_bigint::BigUint; + let n = n.try_into().ok()?; + #[tailcall::tailcall] + fn tail_recursive_factorial(n: u16, acc: BigUint) -> BigUint { + match n { + 0 => acc, + _ => tail_recursive_factorial(n - 1, acc * n) + } + } + return Some(tail_recursive_factorial(n, 1u8.into())); +} + fn Q(a: usize, b: usize) -> usize { if a < b { return 0;