r/ProgrammingLanguages • u/dwaynecrooks • Oct 13 '26
Recursion without Recursive Bindings
https://blog.tinyinterpreters.dev/posts/recursion-without-recursive-bindings/I explain how to implement a certain recursive function without the use of any recursive bindings in a tiny language called FUN. Then, I apply the same ideas to several more recursive functions so we clearly see the pattern. It begins our exploration into a certain famous combinator.
13
Upvotes
View all comments
Show parent comment
3
u/dwaynecrooks Oct 13 '26
To find the type of
makesumwe can reason in the following way.Let
Xbe the type ofself. Sincenis tested withzero?and is used in subtraction, and both branches return anInt,makesumhas typeX -> Int -> Int.Now, consider the expression
(self self)in the body ofmakesum. It is applied to anIntand its result is subtracted, so it has typeInt -> Int. In(self self), the secondselfis the argument, with typeX, and the firstselfis the function. A function that takes anXand returns anInt -> Inthas typeX -> Int -> Int, so that's the type of the firstself. But both are the same variable, soX = X -> Int -> Int.To see what X would have to be, substitute the equation into itself:
Every substitution leaves an
Xbehind, so the expansion never ends. In fact, no finite type can satisfy the equation: whateverXis, the right-hand side containsXplus two more arrows, so it's always bigger thanX.A finite type is one you can write out completely with a finite expression. In a simple type system, types are defined by a grammar like:
and every type it produces is finite. So in such a system
Xhas no solution, andmakesumcan't be given a type.This naturally leads to an interesting question: "What does a type system need for
makesumto be typable?". The short answer is that it requires recursive types. The long answer is that it needs a post of its own for me to explain it properly. I haven't reached types as yet on the blog and I need to learn more to explain it well myself so I'd defer till that moment.