r/functionalprogramming • u/wwwtrollfacecom • Jul 14 '24
Question How does memory allocation in functional languages differ from imperitive languages like, say, C?
Context: I'm pretty new to the functional game, and most of my experience has bene with statically typed imperative languages.
To elaborate on the question, how do functional languages handle memory allocation for recursive functions effectively? Take this C program that sums up integers in an array.
int arr = ;
int sum = 0;
for
(I hope the concept's clear here, because i'm not an ocaml guy)
I'd assume this is the defacto way of performing such operations in a functional language, so what makes it nearly as efficient as something like C?
22
Upvotes
View all comments
Show parent comment
3
u/Dry_Criticism_4325 Jul 15 '24
Tail recursive function is like a loop encompassing the whole function. Because the recursive call is last in the function, you can reuse the stack frame as if you looped and assigned new values to the parameter variables in the stack frame.