rhaiscript / book

The Rhai Book.
https://rhai.rs/book
22 stars 22 forks source link

Fixed a link to scripts/for3.rhai #27

Closed peter-lyons-kehl closed 4 months ago

peter-lyons-kehl commented 4 months ago
  1. Fixed a link to scripts/for3.rhai.

  2. Not "fixed" in this PR: The code of this script doesn't reflect its description "for loops with closures". The main/first interpretation of such a description, especially for Rust or other closure-friendly language users, is: a loop (over something iterable) that invokes a closure that receives an item from that iterable (like with Iterator::for_each).

If that (applying a closure to iterated items) is not idiomatic/easy/out-of-the-box, that's OK (even though it's not obvious, not even after reading the Book and using Rhai for several days). But (either way), this description + example pair is still confusing.

Yes, you do imply plural ("s" in "closures"), but the use case in the example still goes against the simplest interpretation of the descriptions.

Thank you for Rhai and the book. Enjoy Rust. (minor update: each --> for_each - I clearly haven't coded in Rust for a week...)

schungx commented 4 months ago

What would you prefer to call it so it is less confusing?

peter-lyons-kehl commented 4 months ago

As-is, this example/script could be called

However,

  1. I'm surprised to see such an example at all - I don't see it useful (as-is). Yes, we could store closures for some event handlers...
  2. Related: Seeing https://rhai.rs/book/ref/arrays.html#built-in-functions and https://rhai.rs/book/language/arrays.html#examples raises a question whether there is for_each for iterators/iterable data - other than arrays. It doesn't seem so, but it takes a lot of time to figure out. If there is no for_each (or other way) to run a closure on a non-array Iterator/similar, then users want to hear about this upfront - whether in this part of the Book, or some more suitable place, or better: both (since, there is some duplication in the Book already - and I find the current rate of duplication beneficial).
schungx commented 4 months ago

Well, the example is useful in that it shows off a textbook case of closures capturing variables throwing off novice closure users.

A novice interpretation of the script would be adding all the squares from zero to max, but it turns out to add max copies of max because of the captured variable which is shared.

Again we'll find this example almost in every programing textbook.