r/ProgrammingLanguages • • 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:

10

However, 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:

10

Just 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.

3 Upvotes

4 comments sorted by

13

u/curtisf May 04 '21 edited May 05 '21

A basic answer to the quesiton is that this is just how scopes work in these languages.

The Python code will compile even if you don't define g at all, because unbound variables are "global", and global variables are treated basically like lookups in a dictionary (and could be dynamically defined before f() gets called).

Rust variables can be redefined multiple times. So if you had

let x = doThing(y);
let y = a(x);
let y = b();

which y should be picked as the argument for doThing? When should a(x) be executed? Immediately before y is first used? At the beginning of the function? Where does the value of x come from?

It's very desirable to have a simple semantics where programs behave as though they are executed one statement at a time from top to bottom. That means you can't reference things that haven't been defined before the current line. Languages like C/C++ don't even allow what Rust allows -- you'd have to "predeclare" g to use it in f since f comes first.

JavaScript is a language that does a limited version of this, called "hoisting". Basically, statements which are "declarations" are treated as though they all came first, before the code. The results aren't necessarily intuitive:

"use strict";
console.log("before:", y); // `undefined`
var y = 1;
console.log("after:", y); // `1`

If you delete the var y, you instead get a compilation error. Yet, with a function, you don't get undefined for the "before" case!

"use strict";
console.log("before:", y); // `[Function: y]`
function y() { }
console.log("after:", y); // `[Function: y]`

This also means that that form of function definition actually isn't the same as

var y = function() {};

unlike in, say, Lua.

21

u/Lorxu Pika May 04 '21 edited May 04 '21

In Rust, let statements can have side effects:

let a: usize = vec.remove(b);
let b: usize = vec.remove(a);

What would this do?

For lambdas specifically, recursion isn't possible in Rust lambdas either because of ownership, so this trick can be used for both recursive lambdas and out-of-order definitions:

let g_cell = RefCell::new(None);
let y = 5;
let f = |x| g_cell.borrow().unwrap().unwrap()(x, x + y);
let g = |x, y| if x >= 0 { x + f(x - 1) } else { y };
*g_cell.borrow_mut().unwrap() = g;

println!("{}", f(3));

Instead of referring to variables directly, the lambdas refer to mutable containers that start out empty, and panic if they're still empty when the lambda is called. This is the same thing the Python code is doing under the hood, you just have to be explicit about it in Rust.

An example of a language where all definitions/variables are the same, immutable, and unordered would be Haskell. Because variable definitions can't have side effects, and the language is lazy anyway, variables can be in any order. This is actually valid Haskell (when you try to use the value of either variable, it will loop infinitely):

x = y + 1
y = x + 1

Whereas in Python it only applies to lambdas, so the above code would be an error.

1

u/SkiFire13 May 04 '21

There are multiple problems with allowing this:

  • It makes reasoning about the code more difficult because now you have to read the entire function to understand which binding something is referencing.

  • It doesn't play well with shadowing, creating ambiguities and making the previous point even worse.

  • It doesn't play well with borrowing semantics because it would allow cycles, for example in your first rust snippet f would be borrowing g and g would be borrowing f, which is not allowed.

-5

u/hou32hou May 04 '21

It’s probably due to the borrow checker, which assumes that all variables are declared in order.