elm-community / maybe-extra

Convenience functions for working with Maybe.

Home Page:http://package.elm-lang.org/packages/elm-community/maybe-extra/latest

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add `expect : Bool -> Maybe ()`

LightAndLight opened this issue · comments

In Haskell: https://hackage.haskell.org/package/base-4.15.0.0/docs/Control-Monad.html#v:guard

expect : Bool -> Maybe ()
expect b = if b then Just () else Nothing

This is is used to short-circuit Maybe computations based on a condition:

Maybe.expect thisMustBeTrue |>
  Maybe.andThen (\() ->
    -- only run when the condition is true
  )

On its own this function seems to do so little that it's not worth adding. But I see the use case there, and I wonder if it could be addressed more directly, with something like

if : (() -> a) -> Bool -> Maybe a
if fn predicate =
  if predicate then
    Just (fn ())
  else
    Nothing
    
True
|> Maybe.Extra.if (\() -> "ok")
-- Just "ok"

(Just a rough sketch, it'd need a different name.)

I have two concerns:

  1. It encourages using booleans and ifs which often mean data models that have invalid states. I've turned down previous feature requests for that reason. That's not a deal breaker; Maybe.Extra is a fine place to put useful but slightly ugly functions (for example, isJust has this problem but definitely belongs here), but I think it requires being more careful that its usefulness will outweigh those problems.
  2. It's not that hard to reimplement when needed, and I'm not sure it'd be a common enough use case to make it worth including here. Can you link to examples in real Elm or Haskell codebases that show people going out of their way to implement this or similar functions on their own, or examples where this or a similar function would be useful?

In general, I like to be skeptical and conservative about what should be included. There could be something good here, but you have to show it'll be good.