2 ms·
> What’s a example of these macros being used usefully? Sure, here are a couple examples I found from grepping my src directory. roguelikelike game I made for
by stevelosh 8y ago
> What’s a example of these macros being used usefully?
Sure, here are a couple examples I found from grepping my src directory.
roguelikelike game I made for a game jam: https://github.com/sjl/vintage/blob/master/src/main.lisp#L193 https://github.com/sjl/vintage/blob/master/src/main.lisp#L19...
prolog compiler: https://github.com/sjl/temperance/blob/master/src/compiler/3-flattening.lisp#L115 https://github.com/sjl/temperance/blob/master/src/compiler/3...
cl port of robotfindskitten: https://github.com/sjl/sattyrday/blob/master/src/002-afk/main.lisp#L213 https://github.com/sjl/sattyrday/blob/master/src/002-afk/mai...
generative art lib: https://github.com/sjl/flax/blob/master/src/drawing/api.lisp#L153 https://github.com/sjl/flax/blob/master/src/drawing/api.lisp... https://github.com/sjl/flax/blob/master/src/looms/004-turtle-curves.lisp#L67 https://github.com/sjl/flax/blob/master/src/looms/004-turtle...
There are plenty of other things that use various versions of these macros too. ASDF uses them all over the place. And of course Clojure code uses their versions. A Github search for when-let and if-let will give a lot of examples (though you have to wade through all the import matches... unfortunately Github search doesn't let you search for literal strings like "when-let (" to exclude those).
> Why not use `if` and `when` directly?
Convenience, especially when you have multiple in a row:
(when-let ((a (foo))
(b (bar))
(c (baz)))
(blah a b c))
; =>
(let ((a (foo)))
(when a
(let ((b (bar)))
(when b
(let ((c (baz)))
(when c
(blah a b c)))))))
> Is creating new names for variables — which is what `if-let` and `when-let` seems to contribute — that common of a pattern?
I'm not sure what "new names for variables" means here. `let` (and these convenience macros) defines local variables. People create local variables for things pretty often.
- WalterGR 8y agoThanks. > I'm not sure what "new names for variables" means here. All the examples I could find were of the template (when-let ((name1 scalar1) (name2 scalar2) ...) where presumably the `scalar`s were standins for existing named bindings. Same for `if-let`. I wasn't awake enough to contemplate that the `scalar`s above could probably be arbitrary expressions. But skimming your blog post again, I do see this example about half-way through: (let* ((name (read-string)) (length (length name))) ; ... )