Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

FWIW: this exact scenario (capture a local and add it to the lambda's argument) is treated in the Rust book on closures, and the solution picked isn't yours. They want to use Box::new() to explicitly allocate a heap block to track the closure (in C++ the compiler does this for you and puts it into the function type):

https://doc.rust-lang.org/book/closures.html

I'm not expert enough to decide which is "official". But honestly... this is really not a situation where Rust shines aesthetically.



This is because "impl Trait" was accepted for stabilization about a week ago; the book only covers stable things.


C++ actually has the same problem; you can't specify the return value of an unboxed lambda. The differences there are that C++ lets you deduce function return types since C++14, something Rust doesn't want to support, and that boxing is done through a special std::function type, rather than a normal heap pointer.


> something Rust doesn't want to support

Well, in this way. "impl Trait", which was just accepted for stabilization, will let you return unboxed closures.


The reason Box is used there is that the type of a closure in Rust is anonymous, so can't be named as a return type. Once the `impl Trait` syntax for returns is available, the heap allocation won't be necessary any more, because you'll be able to write `fn factory() -> impl Fn(i32) -> i32 {`


So... a three-character capture list is ugly, but that extra impl clause is... fine? Obviously we shouldn't be getting into a Rust vs. C++ flame war in a clang thread, but would you at least agree that (relative to python) both language have significantly more verbose syntax owing to the interaction between closures and the languages data models?

Edit to clarify (to the extent of my rust understanding anyway): C++ didn't want to implicitly suck in external variables by reference and makes the programmer explicitly flag them as references. Rust has a borrow checker, so it can skip this part and simplify the syntax. But Rust's type system has no good way to implicitly figure out the full type of a lambda by its signature, so if you want to pass one around you need to specify its whole type signature twice, once in the expression itself and then again in the signature of the function that will receive or return it.

You pays your money and you makes your choice. Neither language is really a good fit for anonymous functions in the sense that Lisp was.


The extra syntax in this case is all about static typing (and in the case of Rust, exacerbated by having lifetimes as part of the type).

> But Rust's type system has no good way to implicitly figure out the full type of a lambda by its signature, so if you want to pass one around you need to specify its whole type signature twice, once in the expression itself and then again in the signature of the function that will receive or return it.

Rust has no problem figuring out the type of the lambda. But the type of the lambda is anonymous, and unique to that particular lambda. That type is guaranteed to implement the Fn trait, so that's what you specify when you need to return it. You don't need to specify it twice, however - I'm not sure how that follows from the snippet above?

And C++ has the same exact problem: C++ lambdas also each have their own unique type. However, C++ doesn't have traits at all. In C++, if you want to return a lambda, you'd use std::function, which is roughly analogous to Rust's Box<> for functions in this case - you can't just return the lambda directly (well, you can, but only in a context where the return type is implicit and can be inferred from usage - e.g. when returning from another lambda).


In C++14 and later you can return a lambda by using auto as a return type, which compared to impl Trait is shorter but less strongly typed (so more prone to confusing errors).


> So... a three-character capture list is ugly

IMO, it's 'ugly' not because "[=]" is inherently syntactically ugly, but because of all the variations of capture lists and the subtlety of the differences.

> but that extra impl clause is... fine?

It's not great - in fact, 'impl Trait' is a pretty subtle feature as well. But I think it's more principled.

> would you at least agree that (relative to python) both language have significantly more verbose syntax

Yes…

> owing to the interaction between closures and the languages data models?

…Not really. I'll elaborate later in the post.

> so if you want to pass one around you need to specify its whole type signature twice, once in the expression itself and then again in the signature of the function that will receive or return it.

No, you don't. Generally speaking, it needs to be specified at most once, sometimes zero times. In my example:

    fn adder(amount: u32) -> impl Fn(u32) -> u32 {
        move |x| x + amount
    }
the type is only written once. Admittedly, the expression has its own list of arguments ("|x|" versus "(u32)" in the type), but in the expression, only the names are specified, not types.

The caller of `adder` generally wouldn't need to specify the type:

    let a = adder(1);
    println!("{}", a(2)); // 4
…but if it's stored in a struct or passed across additional function boundaries, it may have to be repeated.

When would it have to be specified zero times? Well, for one case, if there aren't any function boundaries involved:

    let amount = 1;
    let adder = |x| x + amount;
    println!("{}", adder(amount));
But also, higher-order functions are often defined once and used many times. For example, the `map` method on Iterator is defined in the standard library with a full (generic) type signature, but I don't need to declare any types to use it:

    let v = Vec::from_iter(vec![2, 3, 4].iter().map(|x| x + 2)));
    println!("{:?}", v);
Admittedly there's a lot more noise there in general than Lisp or Python, but a lot of that is a desire to be explicit about allocations, not directly related to anonymous functions.

FWIW, not doing type inference across across function boundaries is a semi-artificial limitation. Haskell can do it just fine despite being statically typed, and although Haskell has very different implementation strategies, that's not related to type inference. C++ now sort of does it with `auto`, but only does 'forward reasoning' - i.e. it can deduce the type of an operation's result from the types of its operands, but not vice versa. Rust has true type inference, but it eschews global type inference (across functions) mainly because of a tendency to cause hairy/confusing errors in larger programs. (There are also compilation time concerns, but they're not the primary reason AFAIK.) I suppose you can say that dynamically typed languages are easier to understand when they go wrong, compared to hairy Haskell errors - but I'm not sure to what extent that's actually true, as opposed to functional programmers just tending to use more complex types.

By the way, C++(14) actually doesn't require the lambda argument type to be specified in this case. This works fine:

    auto adder(int amount) {
        return [=](auto x){ return x + amount; };
    }
(but not because of type inference; rather, the returned closure implements operator() for any argument. Also, 'amount' can't be 'auto', which is also an arbitrary limitation, but the rationale is pretty confusing to me considering that the return type can be 'auto'.)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: