r/ProgrammingLanguages • u/Vigintillionn • Jun 11 '25
Memory management in functional languages
Hello all, I'm an undergrad student who's very interested in compilers and language design.
As a passion project I'm working on a functional language which leans a lot on the compiler. My goal is to make the functional programming Rust. The compiler does all the heavy lifting of checking and guaranteeing safety at zero cost at runtime.
I've been stuck at how I should implement memory management. I don't feel like using a garbage collector as that kind of goes against the purpose of the language. I then considered a reference counter, but that kind of makes cyclic data structures impossible to make and also requires extra run time checks. So then I figured I could maybe use a borrow checker. Now I wonder is this the right approach for a functional language? How do functional languages handle lifetimes? As everything is immutable and references are usually implicit, is it unusual for a functional language to work with explicit references? What about stack and heap allocations? I know Haskell allocates everything on the heap, but with a borrow checker I should be able to leverage the stack as well, right?
I'm hoping to get some insights into this and am thankful for every response!
View all comments
Show parent comment
2
u/matthieum Jun 12 '25
Immutability by default goes a long to preventing cycles from being formed.
Tying the knot usually requires the ability to define values recursively, or some other such shenanigans, for example
list = [1] + listwould form an infinite list of ones.Maybe, maybe not?
Language semantics are mostly completely orthogonal to multi-threading.
Multi-threading is, to a degree, mostly a property of the runtime -- ie, implementation details -- but if you're trying to optimize the runtime, then you may wish to "leak" some of those details back to the semantics layer. Distinguishing between values that can be shared across threads & values that cannot is one such leak. From a language perspective, it's fairly uninteresting, but it enables runtime optimizations...
Off the top of my head, some optimizations are:
Lazy<T>which doesn't evaluateTuntil the first access, a non-atomic version is much simpler, and faster, than an atomic one.