Skip to content

Add lazily evaluated versions of the conditional functions for applicatives and monads#313

Open
JoelLefkowitz wants to merge 7 commits intopurescript:masterfrom
JoelLefkowitz:lazy-monadic-actions
Open

Add lazily evaluated versions of the conditional functions for applicatives and monads#313
JoelLefkowitz wants to merge 7 commits intopurescript:masterfrom
JoelLefkowitz:lazy-monadic-actions

Conversation

@JoelLefkowitz
Copy link
Copy Markdown

@JoelLefkowitz JoelLefkowitz commented Jan 31, 2025

ifM, whenM and unlessM are really helpful for handling monads expressively. However, they require both of the possible outputs to be constructed. This can be problematic when the Monad is Effect, as PureScript is strictly evaluated, since both the side effects will still need to be constructed, even if they are not launched. This is because they may be expensive to compute especially if they use the imported JS functions.

Here is an example where a lazily evaluated version ifM' would be helpful:

create :: User -> Effect String
update :: User -> Effect String
exists :: User -> Effect Boolean

main :: Effect Unit
main = do
  response <- ifM' exists update create user
  log response

This PR creates lazy versions of each of the conditional functions for Applicatives and Monads:

  • ifM'
  • unless'
  • unlessM'
  • when'
  • whenM'

This is following the same approach as maybe':

Similar to maybe but for use in cases where the default value may be
expensive to compute. As PureScript is not lazy, the standard maybe has
to evaluate the default value before returning the result, whereas here
the value is only computed when the Maybe is known to be Nothing.

maybe' :: forall a b. (Unit -> b) -> (a -> b) -> Maybe a -> b
maybe' g _ Nothing = g unit
maybe' _ f (Just a) = f a

Checklist:

  • Added the change to the changelog's "Unreleased" section with a reference to this PR (e.g. "- Made a change (#0000)")
  • Linked any existing issues or proposals that this pull request should close
  • Updated or added relevant documentation
  • Added a test for the contribution (if applicable)

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants