polysemy-research / polysemy-zoo

:monkey::panda_face: Experimental, user-contributed effects and interpreters for polysemy
BSD 3-Clause "New" or "Revised" License
70 stars 21 forks source link

FinalState Effect #23

Closed isovector closed 5 years ago

isovector commented 5 years ago
data FinalState s m a where
  GetFinal :: FinalState s m s

makeSem ''FinalState

runFinalState
    :: Member Fixpoint r
    => s
    -> Sem (State s ': FinalState s ': r) a
    -> Sem r a
runFinalState s m = mdo
  ~(s', a) <-
    interpret
      \case
        GetFinal -> pure s'
      (runLazyState s m)
  pure a

Get the final value of a state effect.

KingoftheHomeless commented 5 years ago

This actually becomes implementable once https://github.com/polysemy-research/polysemy/pull/187 is merged. (The current semantics of Fixpoint isn't lazy enough). In fact, an example implementation is part of the tests for that pull request.

KingoftheHomeless commented 5 years ago

This can be generalized to the following Input interpreter:

------------------------------------------------------------------------------
-- | Runs an 'Input' effect by running a monadic action after the 'Sem' has
-- completed, and then providing the result to each request recursively.
runInputFixSem :: forall i r a
                . Member Fixpoint r
               => Sem r i
               -> Sem (Input i ': r) a
               -> Sem r a
runInputFixSem m sem = do
  rec
    a <- interpret (\Input -> pure i) sem
    i <- m
  return a

Such that:

runFinalState :: Members '[State s, Fixpoint] r
              => Sem (FinalState s ': r) a
              -> Sem r a
runFinalState =
    runInputFixSem get
  . reinterpret (\GetFinal -> input)

Is runInputFixSem worth adding to polysemy or polysemy-zoo?

isovector commented 5 years ago

whoa.

KingoftheHomeless commented 5 years ago

I'll take that as a "yes" 😄 I'll prepare a pull request for polysemy-zoo. With perhaps some other Fixpoint goodies...

isovector commented 5 years ago

how much easier would life be if there were only one repository?

KingoftheHomeless commented 5 years ago

I like polysemy-zoo. Lower barrier to entry for newcomers to contribute, a good place to put stuff we're unsure of or is just straight-up crazy, and we're a little less stringent about avoiding additional dependencies here. Two "official" repos is a good thing to have, I feel.