Commit Graph

2 Commits

Author SHA1 Message Date
Auke Booij
3833aaaba9 server: simplify interpretation of concrete monads into abstract arrows
During the preparation of [my talk on monad interpretation](https://www.youtube.com/watch?v=cRh56LGzwas), I realized that the interpretation technique is not lawful for monad transformers in general. This fixes that, while also simplifying the approach a little bit.

PR-URL: https://github.com/hasura/graphql-engine-mono/pull/4134
GitOrigin-RevId: 7296a44185e6a87a81ac7efcdd9c7bdd9665a4e3
2022-04-04 12:36:35 +00:00
Auke Booij
b535257251 Avoid Arrows by interpreting monads
TL;DR
---

We go from this:
```haskell
  (|
    withRecordInconsistency
      ( (|
          modifyErrA
            ( do
                (info, dependencies) <- liftEitherA -< buildRelInfo relDef
                recordDependencies -< (metadataObject, schemaObject, dependencies)
                returnA -< info
            )
        |) (addTableContext @b table . addRelationshipContext)
      )
    |) metadataObject
```
to this:
```haskell
  withRecordInconsistencyM metadataObject $ do
    modifyErr (addTableContext @b table . addRelationshipContext) $ do
      (info, dependencies) <- liftEither $ buildRelInfo relDef
      recordDependenciesM metadataObject schemaObject dependencies
      return info
```

Background
---
We use Haskell's `Arrows` language extension to gain some syntactic sugar when working with `Arrow`s. `Arrow`s are a programming abstraction comparable to `Monad`s.

Unfortunately the syntactic sugar provided by this language extension is not very sweet.

This PR shows how we can sometimes avoid using `Arrow`s altogether, without loss of functionality or correctness. It is a demo of a technique that can be used to cut down the amount of `Arrows`-based code in our codebase by about half.

Approach
---

Although _in general_ not every `Monad` is an `Arrow`, specific `Arrow` instantiations are exactly as powerful as their `Monad` equivalents. Otherwise they wouldn't be very equivalent, would they?

Just like `liftEither` interprets the `Either e` monad into an arbitrary monad implementing `MonadError e`, we add `interpA` which interprets certain concrete monads such as `Writer w` into specific arrows, e.g. ones satisfying `ArrowWriter w`. This means that the part of the code that only uses such interpretable effects can be written _monadically_, and then used in _arrow_ constructions down the line.

This approach cannot be used for arrow effects which do not have a monadic equivalent. In our codebase, the only instance of this is `ArrowCache m`, implemented by the `Rule m` arrow. So code written with `ArrowCache m` in the context cannot be rewritten monadically using this technique.

See also
---
- #1827
- #2210

PR-URL: https://github.com/hasura/graphql-engine-mono/pull/3543
Co-authored-by: jkachmar <8461423+jkachmar@users.noreply.github.com>
GitOrigin-RevId: eb79619c95f7a571bce99bc144ce42ee65d08505
2022-02-22 18:09:50 +00:00