Discussion of the Fennel programming language for contributors and users


Technique: using let for Rust-esque variable shadow chains

Message ID
Download raw message

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":

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:

(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:

(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)]

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

Benaiah Mischenko