Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are idempotent functions the same as pure functions?

I read Wikipedia's explanation of idempotence. I know it means a function's output is determined by it's input. But I remember that I heard a very similar concept: pure function. I Google them but can't find their difference...

Are they equivalent?

like image 478
Lai Yu-Hsuan Avatar asked Jan 26 '11 03:01

Lai Yu-Hsuan


People also ask

What does it mean when a function is idempotent?

Idempotence, in programming and mathematics, is a property of some operations such that no matter how many times you execute them, you achieve the same result. In programming, idempotence can be a property of many different code elements, including functions, methods, requests and statements.

What is meant by pure functions?

In computer programming, a pure function is a function that has the following properties: the function return values are identical for identical arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams), and.

Is print a pure function?

Yes, print is a pure function. The value it returns has type IO () , which you can think of as a bunch of code that outputs the string you passed in. For each string you pass in, it always returns the same code.

What are pure functions and modifiers?

A function that does not modify any of the objects it receives as arguments. Most pure functions are fruitful. modifier: A function that changes one or more of the objects it receives as arguments. Most modifiers are fruitless.


2 Answers

An idempotent function can cause idempotent side-effects.

A pure function cannot.

For example, a function which sets the text of a textbox is idempotent (because multiple calls will display the same text), but not pure.
Similarly, deleting a record by GUID (not by count) is idempotent, because the row stays deleted after subsequent calls. (additional calls do nothing)

like image 144
SLaks Avatar answered Oct 20 '22 10:10

SLaks


A pure function is a function without side-effects where the output is solely determined by the input - that is, calling f(x) will give the same result no matter how many times you call it.

An idempotent function is one that can be applied multiple times without changing the result - that is, f(f(x)) is the same as f(x).

A function can be pure, idempotent, both, or neither.

like image 22
Anon. Avatar answered Oct 20 '22 09:10

Anon.