These sorts of optimizations can and should be handled by a (sufficiently smart (tm)) compiler. Common Lisp/SBCL is usually sufficiently smart. I know not everyone likes Common Lisp, but at least I would have tested it with something more performant that Guile, like Chicken Scheme (my favorite!), Chez Scheme, etc. I like Guile and its purpose as a universal scripting language. However, its performance issues are well…
Part of the problem is that raw Scheme is spectacularly underspecified. It also doesn't help that Schemes like Guile are also interactive. The domain of an interactive language and a "compiled" language are quite different. Given the entirety of the program made available to the compiler all at once, there are high level derivations that can happen notably through flow analysis to let the compiler make better decisio…
https://bibliography.selflanguage.org/_static/dynamic-deopti...