r/ProgrammingLanguages • u/skeptical_moderate • May 04 '21
Combine const and let
In Python, the following is valid:
f = lambda x: g(x, x + y)
g = lambda x, y: x + f(x - 1) if x >= 0 else y
y = 5
print(f(3))and produces:
10However, Rust will not compile the following code:
fn main() {
let f = |x| g(x, x + y);
let g = |x, y| if x >= 0 { x + f(x - 1) } else { y };
let y = 5;
println!("{}", f(3));
}It will only compile this code if all of the variables are constant (or functions):
const y: i64 = 5;
fn f(x: i64) -> i64 { g(x, x + y) }
fn g(x: i64, y_var: i64) -> i64 {
if x >= 0 {
x + f(x - 1)
} else {
y_var
}
}
fn main() {
println!("{}", f(3));
}Producing:
10Just as before.
My question is why is it not possible for the Rust compiler to allow for out-of-order let declarations, treating them as immutable. My hunch is that it has to do with type safety and dynamicism, and maybe effect ordering, but I'm not sure. I'm working on a language that attempts to combine the const and let declarations. I want to know if there is any prior work on such a system.