why closures are part of scala or any functional programming language

262 views Asked by At

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

1

There are 1 answers

2
Dmytro Mitin On

Please consider the following example

def factorial(n: Int): Int = {
  lazy val loop: (Int, Int) => Int = 
    (i, acc) =>
      if (i == n + 1) acc
      else loop(i + 1, acc * i)

  loop(1, 1)
}

This is tail-recursive version of factorial with iterating from 1 to n.

From FP point of view all functions here (either Scala methods or actual scala.Functions) 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 (namely n).

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)