make an action idempotent
Clojure.core has a function called memoize
. You probably already know what it does, but just to be on the same page, memoize
takes a function and returns a new function. The new function is just like the argument you pass it, but it has a superpower. It's now cached. It will remember any arguments you pass it, and the return value it found, and give it to you without doing all the work. Of course, it has to do the work the first time, but after that, it's all cached.
You can do this same thing, but instead of giving a function a superpower of being cached, you can make it idempotent. Let's say I had a function that connected to an SMTP server to send an email. I don't want to send the email twice, but I want to be able to retry in case it didn't succeed. So I make the action idempotent so the duplicates don't matter. And what does it mean to be the "same email"? There needs to be a notion of identity.
Write a function called idempotent-by
that takes a function and returns a new function that is like the original except calling it twice on the same thing does the action only once. The first argument to idempotent-by
, before the function in question, should be another function that defines the key. Just like group-by
takes a keyfn, idempotent-by
takes a keyfn.
(defn idempotent-by [keyfn f]
)