Proposal: (a -> Bool) -> a -> f a

Andreas Abel abela at chalmers.se
Sun Dec 21 11:33:36 UTC 2014


On 21.12.2014 12:28, Oliver Charles wrote:
> I tend to use `pure` and `mfilter` for this case:
>
> \x -> fromMaybe 0 $ mfilter (> 0) $ pure (x - 10)

That's what I thought as well.

'Alternative' seems like a bit of an overkill.  cond works for 
everything that has 'empty' and is pointed (accommodates singletons).

   import Agda.Utils.Null
   import Agda.Utils.Singleton

   singletonWhen p a = if p a then singleton a else empty

Cheers,
Andreas

> On Sun, Dec 21, 2014 at 10:54 AM, Nikita Volkov
> <nikita.y.volkov at gmail.com <mailto:nikita.y.volkov at gmail.com>> wrote:
>
>     I propose to add the following utility function into
>     |Control.Applicative|:
>
>     |cond :: (Alternative f) => (a -> Bool) -> a -> f a
>     cond p a = if p a then pure a else empty
>     |
>
>     Following is a typical use case:
>
>     |\x -> fromMaybe 0 $ cond (> 0) $ x - 10
>     |
>
>     which is the same as
>
>     |\x -> let y = x - 10 in if y > 0 then y else 0
>     |
>
>     Why the first one is better:
>
>      1.
>
>         The control flow is evident and goes from right to left step by
>         step.
>         It’s not scattered around like in the second example.
>
>      2.
>
>         No need to interrupt to imagine a name for a temporary variable.
>
>      3.
>
>         Less noise.
>
>     Now, since it’s generalised to |Alternative| one can imagine tons of
>     other useful cases for this.
>
>     Alternative titles:
>
>       *
>
>         |conditional|
>
>       *
>
>         |partial|
>
>     Best regards,
>     Nikita
>
>>
>     _______________________________________________
>     Libraries mailing list
>     Libraries at haskell.org <mailto:Libraries at haskell.org>
>     http://www.haskell.org/mailman/listinfo/libraries
>
>
>
>
> _______________________________________________
> Libraries mailing list
> Libraries at haskell.org
> http://www.haskell.org/mailman/listinfo/libraries
>


-- 
Andreas Abel  <><      Du bist der geliebte Mensch.

Department of Computer Science and Engineering
Chalmers and Gothenburg University, Sweden

andreas.abel at gu.se
http://www2.tcs.ifi.lmu.de/~abel/


More information about the Libraries mailing list