~technomancy/fennel

Discussion of the Fennel programming language for contributors and users

https://fennel-lang.org

Technique: using let for Rust-esque variable shadow chains

Details
Message ID
<87r2ezqwzb.fsf@hector.i-did-not-set--mail-host-address--so-tickle-me>
Download raw message
Greetings,

I've been using Fennel for game development lately, and I've found a
technique I like quite a bit.

As a background: in Rust, it's considered idiomatic to shadow a variable
repeatedly as you perform operations on it[0]. For instance, the
following code prints "x: 8":

```rust
fn main() {
    let x = 10;
    let x = x + 2;
    let x = x * 2;
    let x = x / 3;
    println!("x: {}", x);
}
```

This is especially hand in Rust for reasons having to do with Rust's
type system, but there are two other major benefits: you can't
accidentally re-use earlier values, and you don't have to come up with
new names

A similar pattern can be used in Fennel with let:

```fennel
(let [x 1
      x (+ x 2)
      x (* x 2)
      x (/ x 3)]
  (print (.. "x: " x)))
```

I'm using this in https://git.sr.ht/~benaiah/ludum-dare-nov-2018 for
building a shader effect as follows:

```fennel
(let [eff (moonshine 1024 768 moonshine.effects.crt)
      _ (set eff.crt.feather 0.1)
      _ (set eff.crt.distortionFactor [1.13 1.15])
      eff (eff.chain moonshine.effects.vignette)
      _ (set eff.vignette.radius 0.85)
      _ (set eff.vignette.opacity 0.8)
      eff (eff.chain moonshine.effects.fastgaussianblur)
      eff (eff.chain moonshine.effects.filmgrain)
      _ (set eff.filmgrain.size 2)
      _ (set eff.filmgrain.opacity 0.5)]
  eff)
```

I really like this pattern, and I hope others find it helpful as well.

[0]: https://doc.rust-lang.org/stable/book/second-edition/ch03-01-variables-and-mutability.html#shadowing

Regards,
Benaiah Mischenko