Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is println considered an impure function?

I'm reading the book programming in scala, and it is said :

... in this case , its side effect is printing to the standard output stream.

and I don't see where is the side effect, since, for the same input, println will print the same output (I think )
UPDATE
for example any time we call :

println(5)

it will print 5, I don't see a case where calling println(5) will print a value other than 5 !!

like image 436
aName Avatar asked Feb 25 '20 21:02

aName


People also ask

Why is print an impure function?

printf is impure because its result has "side effects" -- specifically, it prints something on the screen (or in a file, etc). If it were pure, then you could call it a billion times and be sure nothing bad would happen.

Is Println a pure function?

Examples of impure functions Conversely, the following functions are impure because they violate the definition. println – methods that interact with the console, files, databases, web services, sensors, etc., are all impure.

What is an impure function in Java?

An impure function is a function that mutates variables/state/data outside of it's lexical scope, thus deeming it “impure” for this reason. There are many ways to write JavaScript, and thinking in terms of impure/pure functions we can write code that is much easier to reason with.

What is pure and impure functions in Java?

An impure function is a function that contains one or more side effects. A pure function is a function without any side effects.


2 Answers

You can tell if an expression has a side effect by replacing the expression with its result. If the program changes meaning, there's a side effect. For example,

println(5)

is a different program to

()

That is, a side effect is any observable effect that isn't encoded in the result of evaluating an expression. Here the result is (), but there's nothing in that value that encodes the fact that 5 has now appeared somewhere on your screen.

like image 69
joel Avatar answered Oct 06 '22 08:10

joel


The side effect is in the state of the computer. Each time you call println() the state of memory changes in order to display given value to the terminal. Or more generally, the state of the standard output stream is changed.

like image 21
Code-Apprentice Avatar answered Oct 06 '22 09:10

Code-Apprentice