SR Bhaskar
SR Bhaskar

Reputation: 908

Pure functions and I/O

I have been reading up on functional programming, and I understand the concept of pure functions and immutable objects and why they apply in functional programming.

I am a bit fuzzy on when and why a function performing I/O will be considered impure:

Or am I missing something?

Upvotes: 3

Views: 1642

Answers (2)

Ingo
Ingo

Reputation: 36349

I/O output - if my pure function has a few alerts or a few system outs, but always returns the same result for the same argument(s), will it still be considered impure and why?

It's not pure anymore, because the side effect changes "the world" so the result is not "the same" anymore.

Harmless example of changing the world: before your function computes, you had 2 lines output on the screen. After computation, there are 3.

Not so harmless example of changing the world: When your program started (which uses your "almost pure" function a lot), you had several gigabytes freespace on your C: drive. Unfortunately, it was started with output redirected to some file on the C: drive, and after a few hours the C: drive run full. This caused some planned nightly run of an important acccounting job to fail. Result: your company didn't have some important numbers at hand at the right time, and it lost money. And you lost your job.

Upvotes: 0

zerkms
zerkms

Reputation: 255015

Pure functions must be referentially transparent.

Any function that involves any IO is not referentially transparent, since its call cannot be replaced with the returned result.

I/O input - If the result of the function does not depend on an I/O input such as a user input or a file read, will it still be considered impure and why?

If it does not - then simply remove any IO reads.

I/O output - if my pure function has a few alerts or a few system outs, but always returns the same result for the same argument(s), will it still be considered impure and why?

It won't be - because of the side effect.

Upvotes: 3

Related Questions