Anonymous Recursive Functions in Racket

https://news.ycombinator.com/rss Hits: 13
Summary

Anonymous recursive functions in Racket Context Some languages, like PowerShell, have “anonymous recursive functions”. That is, normally, a function needs to use a name to refer to itself to recur. But “anonymous recursion” means the language has some special mechanism by which the function can refer to itself without having to explicitly introduce a name. In some contexts, this is called an anaphoric reference. Code Here we show how we can easily implement this feature in Racket. The file anon-rec.rkt implements a macro called lam/anon♻️ , short for "lambda with anonymous recursion". This specifically binds the name $MyInvocation , to mimic the syntax of PowerShell, though the $ here does not mean anything special. Examples The file client.rkt shows several uses of increasing and varying complexity: fact shows a standard factorial definition. How can we confirm that $MyInvocation is really bound to the right invocation? So lucas-or-fib is essentially a glorified version of the Fibonacci function, but the same body (which recurs using $MyInvocation ) can also be used for the Lucas sequence given different initial values. This shows that the recursive function is bound correctly. grid shows that the correct binding occurs even in nested settings. range is a peculiar way to write a standard range-generating function. It exists only to check that “varargs” works properly with lam/anon♻️ . (In case you're wondering, I added lam/anon♻️ to the lambda -like keywords list of DrRacket's Indenting configuration. That's why the layout is so nice.) Utility Jokes aside, why is this useful? I've often had the experience that I'm writing some helper function as a lambda , then half-way through realize it would be nice if the function could recur. But on its own a lambda can't recur, because it's anonymous, and recursion requires a name. So the traditional solution is to rewrite the program: e.g., introduce a letrec , give a name, make this lambda its right-hand side expression, th...

First seen: 2025-09-06 21:27

Last seen: 2025-09-07 09:39