When a program requests some information from an external source (say, from a web server) we usually want it to give up after some amount of time instead hanging indefinitely awaiting a response that may never arrive.

The asum function in Data.Foldable chooses the first feasible action among a list of possibilities.

We initialize two variables:

  1. result is initialized to Nothing. When our imaginary task (doing nothing for two seconds) completes, it assigns the value Just "Task A: ..." to the result variable.
  1. timeout is initialized to False. We fork another thread which waits for one second and then changes it to True.

The race is now on; what we care about now is which of these two variables changes first.

This is where asum comes in. We want to either:

The program pauses here until either of these two actions is able to run.

Printing the resulting string will tell us which of the two possibilities actually ran.

Since Task A takes two seconds and the timeout is one second, the timeout will happen first.

Now we’ll try the same thing again, but with Task B completing in only half a second (500,000 microseconds, written as 500_000 with the comma replaced by an underscore).

The output shows us that the slower Task A times out, whereas the faster Task B succeeds.