DEV Community π©βπ»π¨βπ» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

hzoltan

Posted on

What is an idempotent function?

An idempotent function in computing is a function that you call more than once with the same input parameters, it will have no additional effect.

It comes from mathematics which looks like this:

f(f(x)) = f(x)

Let's let's check an example in Go!

``````package main

import (
"fmt"
"strings"
)

func main() {
definition := "iDeMpoTeNt"

fmt.Println(strings.ToUpper(definition)) // f(x)
fmt.Println(definition)
fmt.Println(strings.ToUpper(strings.ToUpper(definition))) // f(f(x))
}
``````
``````// Output:
IDEMPOTENT
iDeMpoTeNt
IDEMPOTENT
``````

by calling `strings.ToUpper()` on `definition` variable at first, it will make it uppercase. But calling it again with "definition" makes no other additional effects, therefore it is idempotent.

You can try it yourself on the Go Playground!

Update: Why idempotency is useful?

Special thanks to Casper in the comment for sharing a great 15 min long podcast from Eric Normand about idempotence and why it is useful. I think he had an example rich explanation, and it's best for you to listen to his words!

Casper

It took me a while to understand what you meant by `f(f(x)) = f(x)` because your example doesn't show that. For the formula to hold a function must return the same type as the input, while your example modifies the map without returning anything.

A better example of that is the absolute value function `abs`. Because `abs(abs(x)) = abs(x)`. But that is not to say this is the only useful case, your example is definitely useful.

For the future, I can recommend to also explain why it's useful, why we would want idempotence in our code.

This post made me remember an old podcast episode I listened to a long time ago. I can recommend it if you want to learn a bit of the "why" of idempotence.
lispcast.com/what-is-idempotence/

hzoltan

Thanks for the constructive feedback Casper! Also major thanks for sharing Eric's podcast, it really helped me understand the big picture! I hope you don't mind but I edited the post according to your feedback. Thanks a lot and have a great day!

π Friends don't let friends browse without dark mode.

Sorry, it's true.