Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "reading from a file" is not pure function?

In the book of "function programming in Scala", it gives several example of what is "side-effects", one of them is:

  • Reading from or writing to a file

I can understand "writing to a file" is not pure, because it changes the environment. But why "reading a file" is not pure? It doesn't change anything.

See my example:

val readFile: File => String = file => readingTheContentFromFile(file)
like image 636
Freewind Avatar asked Jul 13 '15 07:07

Freewind


1 Answers

A pure function allways returns the same value given the same input. Otherwise it is based on side effects (like changing a file). If you read from a file the results might change without the parameters given to the function changing.

The relevant concept is 'referential transparency'. This means you can substitute a function call and a given set of parameters with the result the function would return. Reading from a file is therefore not referentially transparent!

like image 87
André R. Avatar answered Oct 05 '22 22:10

André R.