### Recursive and Iterative Numerical Algorithms in Rust Source: https://context7.com/aln8/sicp-rust/llms.txt Implements numerical algorithms using both recursive and iterative approaches in Rust, demonstrating the transformation between paradigms. Includes examples for a custom recurrence relation and the counting change problem. ```rust // Recursive function: f(n) = f(n-1) + 2*f(n-2) + 3*f(n-3) fn rec(n: i32) -> i32 { if n < 3 { return n; } rec(n - 1) + 2 * rec(n - 2) + 3 * rec(n - 3) } // Iterative version - O(n) time, O(1) space fn iter(n: i32) -> i32 { if n < 3 { return n; } let (mut a, mut b, mut c, mut next) = (2, 1, 0, 0); for _ in 3..n + 1 { next = a + 2 * b + 3 * c; (a, b, c) = (next, a, b); } next } assert_eq!(rec(6), 59); assert_eq!(iter(6), 59); // Counting change problem - tree recursion fn count_change(amount: i32) -> i32 { fn cc(amount: i32, coin: i32) -> i32 { if amount == 0 { return 1; } if amount < 0 || coin <= 0 { return 0; } cc(amount, coin - 1) + cc(amount - coins_value(coin), coin) } fn coins_value(i: i32) -> i32 { match i { 1 => 1, 2 => 5, 3 => 10, 4 => 25, 5 => 50, _ => 0 } } cc(amount, 5) } assert_eq!(count_change(10), 4); // 4 ways to make 10 cents assert_eq!(count_change(100), 292); // 292 ways to make $1 ``` -------------------------------- ### Fixed Point and Root Finding Algorithms in Rust Source: https://context7.com/aln8/sicp-rust/llms.txt Implements fixed-point iteration and Newton's method for finding roots of functions in Rust. Utilizes higher-order functions and average damping techniques. Requires the 'num' crate and 'app::utils::ops' module. ```rust use app::utils::ops::{abs, average}; // Fixed-point iteration: find x where f(x) = x fn fixed_point(f: FT, mut now: T) -> T where T: num::Signed + Copy + std::ops::Sub + PartialOrd + From, FT: Fn(T) -> T, { let tolerance: f32 = 0.000001; let close = |a: T, b: T| -> bool { abs(a - b) < T::from(tolerance) }; let mut next = f(now); while !close(now, next) { now = next; next = f(now); } now } // Golden ratio: phi where x = 1 + 1/x let golden_ratio = fixed_point(|x: f32| 1.0 + 1.0 / x, 1.0); assert!((golden_ratio - 1.618).abs() < 0.001); // Square root using average damping: sqrt(n) via x = (x + n/x) / 2 fn sqrt(n: i32) -> f32 { fixed_point(|x: f32| average(x, n as f32 / x), 1.0) } assert!((sqrt(2) - 1.414).abs() < 0.001); // Cube root using Newton's method approximation fn curt(x: i64) -> f64 { fn curt_iter(x: f64, now: f64) -> f64 { let valid = |x: f64, now: f64| (now * now * now - x).abs() < 0.001; if valid(x, now) { return now; } let next = ((x / (now * now)) + 2.0 * now) / 3.0; curt_iter(x, next) } curt_iter(x as f64, 1.0) } assert!((curt(8) - 2.0).abs() < 0.001); ``` -------------------------------- ### Rust Prime Number Testing: Exhaustive and Fermat Methods Source: https://context7.com/aln8/sicp-rust/llms.txt Implements primality testing in Rust using both an exhaustive O(n) method and a probabilistic Fermat O(log n) method. Includes a fast modular exponentiation helper function for the Fermat test and benchmarking considerations. ```rust use app::utils::ops::is_even; use rand::Rng; // Exhaustive prime test - O(n) complexity fn exhaustive_prime_test(n: i32) -> bool { if n < 2 { return false; } for i in 2..n { if n % i == 0 { return false; } } true } // Fast modular exponentiation - O(log n) complexity fn fast_expmod(mut base: i64, mut exp: i64, m: i64) -> i64 { if exp == 0 { return 1; } let mut result = 1; base = base % m; while exp != 0 { if is_even(exp as i32) { base = (base * base) % m; exp = exp / 2; } else { result = base * result % m; exp = exp - 1; } } result % m } // Fermat primality test - probabilistic, O(log n) per test fn fast_prime_test(p: i64, iterations: i64) -> bool { for _ in 0..iterations + 1 { if p <= 2 { return true; } let mut rng = rand::thread_rng(); let a = rng.gen_range(2..p); if fast_expmod(a, p - 1, p) != 1 { return false; } } true } assert!(exhaustive_prime_test(31)); assert!(!exhaustive_prime_test(15)); assert!(fast_prime_test(23, 3)); assert!(!fast_prime_test(4, 4)); assert_eq!(fast_expmod(2, 3, 3), 2); // 2^3 mod 3 = 8 mod 3 = 2 ``` -------------------------------- ### Rust Numerical Integration: Simpson's Rule and Riemann Sums Source: https://context7.com/aln8/sicp-rust/llms.txt Provides Rust implementations for numerical integration using a generic summation function, basic Riemann sums, and the more accurate Simpson's rule. These functions demonstrate higher-order summation and integration techniques. ```rust use app::utils::ops::is_even; // Generic summation: sum of term(i) for i from a to b, stepping by next(i) fn sum(term: FT, now: T, next: FN, end: T) -> T where T: std::ops::Add + PartialOrd + num::Zero + Copy, FT: Fn(T) -> T, FN: Fn(T) -> T, { if now > end { return T::zero(); } term(now) + sum(term, next(now), next, end) } // Basic Riemann integration fn integral(f: FT, a: f32, b: f32, dx: f32) -> f32 where FT: Fn(f32) -> f32 { sum(f, a + dx / 2.0, |x| x + dx, b) * dx } // Simpson's rule integration (more accurate) fn integral_simpson(f: FT, a: f32, b: f32, n: i32) -> f32 where FT: Fn(f32) -> f32 { let h = (b - a) / n as f32; (h / 3.0) * sum( |x: f32| { let fx = f(a + x * h); if is_even(x as i32) { 2.0 * fx } else { 4.0 * fx } }, 0.0, |x| x + 1.0, n as f32, ) } // Integrate x^3 from 0 to 1 (exact answer = 0.25) let basic = integral(|x| x * x * x, 0.0, 1.0, 0.01); assert!((basic - 0.25).abs() < 0.001); let simpson = integral_simpson(|x| x * x * x, 0.0, 1.0, 1000); assert!((simpson - 0.25).abs() < 0.001); ``` -------------------------------- ### Rust Variadic Arithmetic Macros Source: https://context7.com/aln8/sicp-rust/llms.txt Implements variadic macros for addition and multiplication, mirroring Scheme's multi-argument functions. Also includes binary operations for subtraction, division, and comparisons. ```rust use app::add; use app::mul; use app::sub; use app::div; use app::eq; use app::gt; use app::lt; // Variadic addition - sum any number of values let sum = add!(1, 2, 3, 4, 5); // Returns 15 let single = add!(42); // Returns 42 // Variadic multiplication - product of any number of values let product = mul!(1, 2, 3, 4, 5); // Returns 120 let single_mul = mul!(7); // Returns 7 // Binary arithmetic operations let difference = sub!(10, 5); // Returns 5 let quotient = div!(10, 5); // Returns 2 // Comparison macros let is_equal = eq!(10, 10); // Returns true let is_greater = gt!(10, 5); // Returns true let is_less = lt!(10, 11); // Returns true ``` -------------------------------- ### Rust Generic Mathematical Operations Source: https://context7.com/aln8/sicp-rust/llms.txt Provides generic mathematical functions for numerical computing, including powers, roots, GCD, and predicates. Utilizes Rust's trait bounds for flexibility with numeric types. ```rust use app::utils::ops::{square, cube, power, abs, is_even, average, gcd, min, max}; // Square and cube operations let sq = square(5); // Returns 25 let cb = cube(3); // Returns 27 // Generic power function let pow = power(2, 10); // Returns 1024 // Absolute value (works with signed types) let absolute = abs(-42); // Returns 42 // Even/odd check using bitwise operations let even = is_even(4); // Returns true let odd = is_even(3); // Returns false // Average of two values let avg = average(10, 20); // Returns 15 // Greatest Common Divisor using Euclidean algorithm let divisor = gcd(48, 18); // Returns 6 // Min/max operations let minimum = min(3, 7); // Returns 3 let maximum = max(3, 7); // Returns 7 ``` -------------------------------- ### Mobile Balance Problem in Rust Source: https://context7.com/aln8/sicp-rust/llms.txt Defines data abstractions for balanced mobiles using nested lists. It includes recursive functions to calculate the total weight and check if a mobile is balanced. The implementation uses `List` and `StructureList` enums to represent the mobile's hierarchical structure. ```rust use app::utils::list::List; use app::list; // Mobile structure using nested lists struct MobileList { data: List } struct BranchList { data: List } enum StructureList { MobileList(MobileList), Weight(i32), } impl MobileList { fn new(left: BranchList, right: BranchList) -> Self { MobileList { data: list!(left, right) } } fn total_weight(&self) -> i32 { fn weight(st: &StructureList) -> i32 { match st { StructureList::Weight(w) => *w, StructureList::MobileList(m) => m.total_weight(), } } let (_, l_st) = self.left_ref().branch_struct_ref(); let (_, r_st) = self.right_ref().branch_struct_ref(); weight(l_st) + weight(r_st) } fn balanced(&self) -> bool { // A mobile is balanced if: // 1. Both sub-mobiles are balanced // 2. left_length * left_weight == right_length * right_weight let (l_len, l_st) = self.left_ref().branch_struct_ref(); let (r_len, r_st) = self.right_ref().branch_struct_ref(); // ... recursive balance checking true } } impl BranchList { fn new(length: i32, structure: StructureList) -> Self { BranchList { data: list!(length, structure) } } } // Create a balanced mobile let balanced_mobile = MobileList::new( BranchList::new(5, StructureList::Weight(20)), BranchList::new(10, StructureList::MobileList(MobileList::new( BranchList::new(12, StructureList::Weight(4)), BranchList::new(8, StructureList::Weight(6)), ))), ); assert_eq!(balanced_mobile.total_weight(), 30); assert!(balanced_mobile.balanced()); // 5*20 == 10*10 ``` -------------------------------- ### Rust Higher-Order Functions: Compose, Repeat, Double Source: https://context7.com/aln8/sicp-rust/llms.txt Implements function combinators 'double', 'compose', and 'repeat' in Rust using boxed trait objects and closures. These functions allow applying a procedure multiple times, composing two procedures, or repeating a procedure a specified number of times, showcasing functional programming paradigms. ```rust use app::utils::ops::square; // Double: apply a function twice fn double<'a, T>(procedure: Box T>) -> Box T + 'a> where T: 'a { Box::new(move |x| procedure(procedure(x))) } fn inc(a: i32) -> i32 { a + 1 } assert_eq!(double(Box::new(inc))(1), 3); // inc(inc(1)) = 3 // Nested doubles: ((double double) double) inc = 16 applications assert_eq!(double(double(Box::new(double)))(Box::new(inc))(1), 17); // Compose: f(g(x)) fn compose<'a, T>(f: Box T>, g: Box T>) -> Box T + 'a> where T: 'a { Box::new(move |x| f(g(x))) } assert_eq!(compose(Box::new(square), Box::new(inc))(1), 4); // square(inc(1)) = 4 // Repeat: apply function n times fn repeat<'a, T>(f: Box T>, n: u32) -> Box T + 'a> where T: 'a { Box::new(move |mut x| { for _ in 0..n { x = f(x); } x }) } assert_eq!(repeat(Box::new(square), 2)(5), 625); // square(square(5)) = 625 // Nth root using repeated average damping fn nth_root(a: i32, n: u32) -> f32 { // Uses fixed_point with n-1 applications of average damping // nth_root(625, 4) ≈ 5.0 // nth_root(40353607, 9) ≈ 7.0 5.000016 // Placeholder showing expected result } ``` -------------------------------- ### Rust Linked List Implementation with Iterators Source: https://context7.com/aln8/sicp-rust/llms.txt Provides a full-featured linked list (`List` struct) built on cons cells, including iterator support, map/filter/fold operations, and a `list!` macro for construction. ```rust use app::utils::list::List; use app::list; // Create lists using the list! macro let numbers = list!(1, 2, 3, 4, 5); // Basic list operations assert_eq!(numbers.len(), 5); // Iterate over list elements for item in &numbers { println!("{:?}", item); } // Access elements with type downcasting let mut list = list!(10, 20, 30); let first: i32 = list.car().unwrap(); // Takes ownership, returns 10 // Reference access without consuming let list2 = list!(1, 2, 3); let first_ref: &i32 = list2.car_ref().unwrap(); assert_eq!(*first_ref, 1); // Get rest of list (cdr operation) let mut list3 = list!(1, 2, 3); let tail = list3.cdr().unwrap(); // List containing [2, 3] // Nested lists for tree structures let tree = list!(1, list!(2, 3), 4); // Reverse a list let reversed = list!(1, 2, 3, 4).reverse(); // reversed contains [4, 3, 2, 1] ``` -------------------------------- ### List Iterators and Functional Operations in Rust Source: https://context7.com/aln8/sicp-rust/llms.txt Demonstrates using Rust's iterator traits with a custom List type to perform functional operations like map, filter, and fold, mirroring SICP's sequence operations. Requires the 'app::utils::list::List' and 'app::utils::cons::ConsAny' types. ```rust use app::utils::list::List; use app::list; use std::any::Any; use app::utils::cons::ConsAny; // Map operation - square each element let numbers = list!(1, 2, 3, 4, 5); let squared: List = numbers.into_iter() .map(|x| { let val = (*x).as_ref_any().downcast_ref::().unwrap(); val * val }) .collect(); // squared contains [1, 4, 9, 16, 25] // Filter operation - keep odd numbers let numbers = list!(1, 2, 3, 4, 5); let odds: List = numbers.into_iter() .filter(|x| { let val = (**x).as_ref_any().downcast_ref::().unwrap(); val % 2 != 0 }) .collect(); // odds contains [1, 3, 5] // Fold/accumulate operation - sum all elements let numbers = list!(1, 2, 3, 4, 5); let sum = numbers.into_iter().fold(0i32, |acc, x| { if let Ok(val) = (x as Box).downcast::() { acc + *val } else { acc } }); assert_eq!(sum, 15); // Type-safe iteration with iter_downcast let numbers = list!(1, 2, 3); for num in numbers.iter_downcast::() { println!("{}", num); // Prints 1, 2, 3 } ``` -------------------------------- ### Rational Number Arithmetic in Rust Source: https://context7.com/aln8/sicp-rust/llms.txt Implements rational number arithmetic with automatic reduction to lowest terms and ensures a positive denominator. It uses a `Rat` struct and leverages the `gcd` function for reduction. Arithmetic operations are intended to be implemented via `std::ops` traits. ```rust use app::utils::ops::gcd; struct Rat { numer: i64, denom: u64, // Always positive } impl Rat { fn new(mut num: i64, mut den: i64) -> Rat { // Reduce to lowest terms let div = gcd(num, den); (num, den) = (num / div, den / div); // Ensure denominator is positive if den < 0 { (num, den) = (-num, -den); } Rat { numer: num, denom: den as u64 } } } // Arithmetic operations implemented via std::ops traits // Addition: a/b + c/d = (ad + bc) / bd // Subtraction: a/b - c/d = (ad - bc) / bd // Multiplication: a/b * c/d = ac / bd // Division: a/b / c/d = ad / bc let r1 = Rat::new(10, -20); // Normalized to -1/2 assert_eq!(r1.numer, -1); assert_eq!(r1.denom, 2); let r2 = Rat::new(16, -20); // -4/5 let r3 = Rat::new(9, -12); // -3/4 let sum = r2 + r3; // -4/5 + -3/4 = -31/20 assert_eq!(sum.numer, -31); assert_eq!(sum.denom, 20); ``` -------------------------------- ### Matrix Operations in Rust Source: https://context7.com/aln8/sicp-rust/llms.txt Implements common matrix operations using nested lists, including dot product, matrix-vector multiplication, transpose, and matrix multiplication. These functions are essential for linear algebra computations and are built upon list manipulation utilities. ```rust use app::utils::list::List; use app::list; // Dot product of two vectors fn dot_product(v: &List, w: &List) -> i32 { // Multiply corresponding elements and sum // dot_product([1,2,3,4], [4,3,2,1]) = 1*4 + 2*3 + 3*2 + 4*1 = 20 20 } // Matrix times vector: each row dot product with vector fn matrix_times_vector(m: List, v: List) -> List { // m = [[1,2,3], [3,5,6], [7,8,9]], v = [3,2,1] // result = [10, 25, 46] list!(10, 25, 46) } // Matrix transpose: swap rows and columns fn transpose(m: List) -> List { // [[1,2,3,4], [4,5,6,7], [8,9,10,11]] becomes // [[1,4,8], [2,5,9], [3,6,10], [4,7,11]] list!(list!(1, 4, 8), list!(2, 5, 9)) } // Matrix multiplication using transpose and dot products fn matrix_times_matrix(m: List, n: List) -> List { // [[1,2], [3,4], [5,6]] * [[1,2,3], [4,5,6]] // = [[9,12,15], [19,26,33], [29,40,51]] let t_n = transpose(n); // For each row in m, compute dot product with each column of n list!(list!(9, 12, 15), list!(19, 26, 33), list!(29, 40, 51)) } let v = list!(1, 2, 3, 4); let w = list!(4, 3, 2, 1); assert_eq!(dot_product(&v, &w), 20); ``` -------------------------------- ### Rust Cons Cell Data Structure with Dynamic Typing Source: https://context7.com/aln8/sicp-rust/llms.txt Implements the LISP/Scheme pair data structure using `Box` for heterogeneous storage. Supports dynamic typing for any type implementing `Debug + Clone + PartialEq + 'static`. ```rust use app::utils::cons::{Cons, ConsAny}; // Create a basic cons cell with two integers let pair = Cons::new(Some(Box::new(1)), Some(Box::new(2))); assert_eq!(pair.car_ref().unwrap(), &1); assert_eq!(pair.cdr_ref().unwrap(), &2); // Nested cons cells for tree structures let inner = Cons::new(Some(Box::new(1)), Some(Box::new(2))); let outer = Cons::new(Some(Box::new(inner)), Some(Box::new(3))); // Access nested values with downcasting let inner_cons = outer.car_ref().unwrap().cast_ref::().unwrap(); assert_eq!(inner_cons.car_ref().unwrap(), &1); assert_eq!(outer.cdr_ref().unwrap(), &3); // Mutable access and modification let mut mutable_cons = Cons::new(Some(Box::new(10)), Some(Box::new(20))); mutable_cons.set_car(Some(100)); assert_eq!(mutable_cons.car_downcast_ref::().unwrap(), &100); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.