Reputation: 267
So let's say we want to deal with computations that can fail using a container similar to Maybe. If I were to specify a typeclass for what I want to do, it'd look something like this:
class Alternative f => Nullable f where
isEmpty :: f a -> Bool
Such that isEmpty x == True
if and only if x = empty
Is there some existing typeclass that I should use for this functionality or should I just use the class above?
EDIT: Some more context
I'm trying to implement matching for logic programming, and I want to be able to have a "not pattern" i.e. "succeed if and only if this program fails, then do ___".
Upvotes: 2
Views: 179
Reputation: 34398
As had been foretold in the comments to danidiaz's answer, base-4.8 generalised the type of null
, making it an easy at reach emptiness test for Foldable
containers:
GHCi> :t null
null :: Foldable t => t a -> Bool
GHCi> null Nothing
True
GHCi> null (Left "An error")
True
GHCi> null []
True
GHCi> import qualified Data.Map as Map
GHCi> null Data.Map.empty
True
Upvotes: 1
Reputation: 27766
Perhaps you could use Foldable
in this manner. Maybe
, []
, Either
, ErrorT
, ExceptT
are all Foldable
. You can just pattern-match on the result of toList
.
And in cases when you want to do something with the results of a successful execution and nothing in case of failure, you can use forM_
directly.
Alternatively, you could use the MonoidNull
typeclass from monoid-subclasses
, that provides the null
predicate.
Upvotes: 5