Murat Kasimov

More about me

Я language (β)

/Я language (β)/Snippets/Asynchronous computations/

Twitter threadSource code

Asynchrony is a relative property - it doesn't describe a computation itself, rather than how it relates to other ones.

By default, all operations with World expressions (input/output related computations) are synchronous. Here is a simple program - it's waiting for an input to print it out back to the standard output:

> input `yok` Await `ha` output

We can replace Await label with Async so that it wouldn't compile. Technically the reason is that such a natural transformation doesn't exist because... it doesn't make any sense:

> input `yok` Async `ha` output

We cannot run something asynchronically while waiting exclusively for its execution.

Let's find a case when it does make sense then - it should be something that we need to wait being executed, artificially crafted time delay in seconds:

> delay s x = threadDelay ( 1000000 * s ) `yo` x

We are glueing these expressions together using a semi-monoidal functor mapping from product to product (lu'yp):

> ... = Enter `ha` delay 3 `hv` A >> `lu'yp` Await `ha` delay 4 `hv` B

Since we are waiting 3 and 4 seconds to tick, in total the code above takes 7 seconds to execute it.

Why would we wait two these delays to happen if we can run them asynchronically and wait both of them to finish? Just replace Await with Async and wait only 4 seconds since it's the longest one:

> ... = Enter `ha` delay 3 `hv` A >> `lu'yp` Async `ha` delay 4 `hv` B

However there is another way to combine these expressions. We used a natural transformation from a product of functors to a functor of products - but we also can use sums instead:

> `yp` : World i `P` World ii `AR_______` World ( i `P` ii ) > `ys` : World i `P` World ii `AR_______` World ( i `S` ii )

More than that, we cannot use lu'ys with Await behaviour, only Async:

> ... = Enter `ha` delay 3 `hv` A >> `lu'ys` Async `ha` delay 4 `hv` B

The code above takes 3 seconds to execute, since it chooses the fastest one.