arliss_obsidian/fp/Classes/Alternative/Plus.md

39 lines
1.0 KiB
Markdown
Raw Permalink Normal View History

2024-09-24 19:53:59 +00:00
Extends [[Alt]] with an empty value:
```haskell
class Alt f <= Plus f where
empty :: forall a. f a
```
> [!info]
> Conceptually, this lives next to [[Applicative|pure]] in my mind; in [[Maybe]] for example `pure` and `empty` are aliases for `Just` and `Nothing`.
In [[Array]], `empty` is empty array `[]`. In [[Maybe]], `empty` is `Nothing`.
The most common place you'll see `empty` is when using [[MaybeT]] as an early return:
```haskell
logDebug :: String -> Effect Unit
logDebug msg = void $ runMaybeT do
env <- MaybeT $ Process.lookupEnv "NODE_ENV"
when (env /= "DEVELOPMENT") empty
lift $ Console.log msg
```
this is equivalent to:
```haskell
logDebug :: String -> Effect Unit
logDebug msg = do
menv <- Process.lookupEnv "NODE_ENV"
case menv of
Just env ->
if env == "DEVELOPMENT" then
Console.log msg
else
pure unit
Nothing -> pure unit
```
> [!info]
> Note that [guard](https://pursuit.purescript.org/packages/purescript-control/docs/Control.Alternative#v:guard) is a shorthand available for `when (..) empty`