leancheck icon indicating copy to clipboard operation
leancheck copied to clipboard

expose the Monad instance for the return type of tiers

Open bfrk opened this issue 5 years ago • 2 comments

I find it peculiar that the monad here is not explicitly exposed, nor even mentioned in the docs. I currently have a module where I define it myself:

newtype Tiers a = Tiers {unTiers::[[a]]} deriving Functor

instance Applicative Tiers where
  pure = return
  (<*>) = ap

instance Monad Tiers where
  return x = Tiers [[x]]
  Tiers mx >>= k = Tiers $ concatMapT (unTiers . k) mx

instance Alternative Tiers where
  Tiers mx <|> Tiers my = Tiers $ mx \/ my
  empty = Tiers []

This allows me to much more easily define Listable instances using do-notation when the allowed elements of a certain data type depend on (and perhaps modify) some state. In my case, I have a state type and another data type representing changes to the state, and for changes to be valid they must be applicable to the current state.

Having these instances also helps to convert existing QC Arbitrary instances to Listable, since Tiers corresponds exactly to QC's Gen monad. In fact, if you don't use any special features of Gen you may generalize your existing code to work with any given generator monad.

Finally, note that this Monad instance is quite different from the one we get without the newtype wrapper (via the standard instance for lists). The latter is in fact quite useless.

bfrk avatar Mar 02 '20 13:03 bfrk

Fair enough. I'll try to work on a LeanCheck sub-module to allow Monadic style generators.

rudymatela avatar Mar 10 '20 23:03 rudymatela

Yes. I am using leancheck's operations on tiers for (something like) "fair" logic programming (breadth first traversal of search space, instead of Prolog-like leftmost traversal)

interface: https://gitlab.imn.htwk-leipzig.de/waldmann/pure-matchbox/-/blob/master/src/Stream/Tiers.hs (the Monad instance is the same as in this issue here?)

application: https://gitlab.imn.htwk-leipzig.de/waldmann/pure-matchbox/-/blob/master/src/Matchbox/Transport.hs#L455

jwaldmann avatar Jun 14 '22 07:06 jwaldmann