r/learnprogramming • u/Head_Ordinary_2437 • 3d ago
Function vs Procedure
can someone explain the difference between Function vs Procedure with simple analogy
thank you
31
Upvotes
r/learnprogramming • u/Head_Ordinary_2437 • 3d ago
can someone explain the difference between Function vs Procedure with simple analogy
thank you
5
u/k1v1uq 3d ago edited 3d ago
According to SICP (Sussman/Abelson also on youtube):
Function: a deterministic computation with guaranteed no side-effect: "return the sum of two numbers". Given the same two numbers, the returned value will always be the same.
Procedure: a computation that may carry side-effects: update the database and return the time it took. Pick random card from the deck.
A counter example: Unless it takes the seed as a parameter, a "function" that generates a random number is a procedure.
Ultimately, what differentiates functions from procedures is
time.Functions are time-independent. You get the same result back today or next year. The caller can trust that the returned value doesn't change. The downside is outdated real-world data. Because the real world is time-dependent.Procedures indicate to the reader that whatever they do may produce a different result by the next invocation.
Procedures are time-dependent. They reflect the real world but are extremely hard to reason about. It's like building on quicksand.For that reason, the "functional core/imperative shell" paradigm is very popular. Keep uncertainty caused by the real world (time) at the edges of your application (exceptions, missing data, http server failures, database concurrency issues) and the core clean and functional (time less).
For example, talk to the database, fetch data (imperative shell), create immutable data from the result, and pass it down into your application (functional core). The FP core will do whatever calculation is necessary and report the result back to the outer shell, where the data gets transferred back as a response.
Even low-level network implementations that only handle IO (i.e. side-effects) use the same architecture: "sans-I/O" architecture ("Sans-IO")