r/functionalprogramming • • 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[5] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
   sum += arr[i];
}

(I hope the concept's clear here, because i'm not an ocaml guy)

let recursive sum array:
    match array:
       [] -> 0,
       first :: rest -> first + sum rest,
end sum

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

10 comments sorted by

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.