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
11
u/wwwtrollfacecom Jul 14 '24 edited Jul 14 '24
Ah, so in tail recursive functions only the last expression is evaluated, meaning that additional stack frames don't have to be allocated for every call. Therefore my implementation is in fact, not that standard way to do stuff. That answers my question, thank you.
edit: "OCaml values don’t all have to be boxed at runtime. Instead, values use a single tag bit per word to distinguish integers and pointers at runtime. The value is an integer if the lowest bit of the block word is nonzero, and a pointer if the lowest bit of the block word is zero."
Cool!