haskus / packages

Haskus packages
https://haskus.org/
24 stars 11 forks source link

Add toVariantMaybe #29

Closed sheaf closed 4 years ago

sheaf commented 4 years ago

This PR adds

toVariantMaybe :: ( a :<? xs ) => a -> Maybe (V xs)

which is in a sense dual to the VMaybe pattern synonym.

I've been writing a program which has an extensible "action" variant type, and want to write actions to a TQueue when the action can be handled. Something like:

signalAction
  :: forall action actions
  .  ( action :<? actions )
  => TQueue (V actions) -> action -> IO ()
signalAction tqueue action = case toVariantMaybe @_ @actions action of
  Just a  -> atomically ( writeTQueue tqueue a )
  Nothing -> pure ()

The constraints in the ToVariantMaybe instances are a subset of the corresponding constraints in the PopVariant instances, so the change in the definition of (:<?) shouldn't have any effect on type-level computations.

hsyl20 commented 4 years ago

LGTM. Thanks!

sheaf commented 4 years ago

Oops, the instances are overlapping. I force-pushed a fix to my branch (c04a6c2), sorry about that.

hsyl20 commented 4 years ago

Fixed. I have added a doctest too.