2 ms·
Can you give an example of a language which is polymorphic in this way and how that looks?
by mmaniac 2y ago
Can you give an example of a language which is polymorphic in this way and how that looks?
- lmm 2y agoHaskell or Scala are the immediate examples. The idiomatic way to write async-style functions in those languages tends to be do notation or for/yield style. E.g. transformFile = do { x <- readFile(...) y = process(x) z <- writeFile(...) } is the equivalent of something like: async transformFile = { x = await readFile(...) y = process(x) z = await writeFile(...) } In Haskell you write exactly the same code when readFile and writeFile are async, or when they're polymorphically async-or-not, your function will just implicitly be as polymorphic as it possibly can be based on the functions it's calling. In Scala you need an explicit type parameter if you want to be polymorphic: def transformFile = for { x <- readFile(...) y = process(x) z <- writeFile(...) } yield () def transformFile[F[_]: Monad] = for { x <- readFile(...) y = process(x) z <- writeFile(...) } yield () The first example is always async, the second example is polymorphic (it's calling readFile[F] and writeFile[F], but those get inferred).
- mmaniac 2y agoAh I've got it. Async is a monad and the function is just polymorphic over Monad m. In the sync case m is Identity. Can you point me in the direction of some libraries which offer functions like these?
- lmm 2y agosttp (HTTP client), http4s (HTTP client/server), quill (database access), fs2 (streaming data processing), I have some vague memory of a gRPC implementation. A lot of stuff that does async in Scala tends to be written in this style because it's almost no extra cost compared to writing it in strictly async fashion.