Add operators for working with unary predicates

+1 for all the suggested operators acting on boolean unary functions (with expansion to general boolean returning functions when we have variadic generics, as mentioned by @allevato)

I frequently find myself wishing for more expressivity when using predicate functions, and so I end up defining these operators so I don’t have to create cluttered little closures:

I also find myself writing things like this manually (in-fact I even pointed one of these out recently SE-0197 — Add in-place remove(where:) - #25 by aidantwoods), so there are at least a few of us already doing this for what it's worth.

Also +1 from me on the suggested composition operator.

I think adding function operators like these is great, and really speaks to welcoming functions as the first-class types that they are by allowing them to be combined or transformed :)

My concern about reusing the standard operators here is that these kind of DSLs don't scale past small demos well. While you can get && and ||, and maybe ^, !=, etc. to work, as soon as you try to use an operator or function that hasn't been overloaded to "lift" it into the predicate DSL, you'll hit a wall (and probably get inscrutable type errors). Furthermore, there are things like ?:, if, and switch that might make sense to interoperate with this DSL but that the language doesn't let you overload, for better or worse, putting fundamental limitations on how transparent the DSL can be. I'd suggest owning the fact this is a specialized DSL and using visibly different operator spellings, like maybe <&&> and <||>. Not only will that make the boundaries of the DSL clear, the type checker will thank you too for not having to deal with a larger overload set for && and || as well.

In the beautiful future where Swift has higher-kinded types and functions are first-class types able to conform to protocols, you could conceivably also treat predicates as an applicative functor, and give them the Haskell-style map/flatMap/flatten core operations too.

10 Likes