By the definition closures are
Scala Closures are functions which use one or more free variables and the return value of this function is dependent of these variable. The free variables are defined outside of the Closure Function and is not included as a parameter of this function.
and the definition of a pure function is
A pure function is a function that depends only on its declared inputs and its internal algorithm to produce its output. It does not read any other values from “the outside world” — the world outside of the function's scope — and it does not modify any values in the outside world.
when functional programming is all about writing code in terms of pure functions,: how come concept like closure is justified in functional programming
please help to clear the understanding
Please consider the following example
This is tail-recursive version of factorial with iterating from
1
ton
.From FP point of view all functions here (either Scala methods or actual
scala.Function
s) are pure i.e. on the same inputs they return the same output and don't have side effects, their calls can be replaced with their results (referential transparency).But
loop
being a closure depends on a parameter from outer scope (namelyn
).Reading a variable (free of side-effects) from outer scope (on contrary to writing) is not considered a side effect.
https://alvinalexander.com/scala/fp-book/definition-of-pure-function/
https://en.wikipedia.org/wiki/Pure_function
https://en.wikipedia.org/wiki/Referential_transparency
What is referential transparency?
https://en.wikipedia.org/wiki/Closure_(computer_programming)