Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a failed computation to a successful one and vice versa

This might very well be a solution seeking a problem ... if so, I beg your indulgence!

Possible implementation:

class Switch' f where
  switch :: f a -> f ()

instance Switch' [] where
  switch []     = [()]
  switch (_:_)  = []

instance Switch' Maybe where
  switch Nothing   = Just ()
  switch (Just _)  = Nothing

The interpretation would be: given a successful computation, make it a failing one; given a failing computation, make it a successful one. I'm not sure, but this seems like it might be sort of the opposite of MonadPlus ... if you squint really hard. ???

Is there a standard typeclass or some other implementation for this concept? What would the underlying math look like, if any (i.e. is this a semigroup, a loop, etc.)?

like image 605
Matt Fenwick Avatar asked Oct 30 '12 20:10

Matt Fenwick


1 Answers

switch :: (Alternative f, Eq (f a)) => f a -> f ()
switch x | x == empty = pure ()
         | otherwise = empty

or

switch :: (MonadPlus m, Eq (m a)) => m a -> m ()
switch x | x == mzero = return ()
         | otherwise = mzero
like image 157
singpolyma Avatar answered Sep 19 '22 15:09

singpolyma