Retry

One of the things I love about functional programming, and Scala in particular is that it feels like you can make new language constructs.  One common pattern I run into is having to do something a few times until hopefully it works.  This is especially relevant when you are calling some remote endpoint that might be busy, slow, or down or whatever.

I found this little gem on stackoverflow:

What’s going on here?  We take an Int and a function.  Then try to call the function.  If it successful then return its value, else recursively call ourselves again until we run out of tries.  If we haven’t succeeded in a certain number of tries then throw the exception the function gave us.

If you don’t fully understand what the @annotation.tailrec does, do yourself a favor and read this article.  It does a great job of explaining it.  But in a nutshell, the Scala compiler can optimize a tail recursive function into a loop, which means no more stack overflows.  Surprisingly, this feature is rare in a lot of modern day languages.  I think in Ruby you can compile it in, Python is philosophically opposed to it.  The more purely functional languages like Clojure, Erlang, and Haskell of course would do better.  Sorry Javascript, you have to trampoline too, how sad for you…  But I’m sure there are a bunch of transpilers that can fix that up, I wonder what Scala.js does there?

Ok so enough of that, the real story is in how easy it in to use this guy.

It’s just that easy you can retry how ever many times you like else throw your exception…
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s