问题
While implementing a refinement type system, I need to put in checks to make sure the types are well-formed. For example, a type like Num[100,0]
shouldn't happen, where Num[lb,ub]
is the type of numbers larger than lb
and smaller than ub
. I then wrote:
-- FORMATION RULES
class RefTy t
where tyOK :: t -> Bool
instance RefTy Ty
where tyOK (NumTy (n1, n2)) = n1 <= n2
tyOK (CatTy cs) = isSet cs
{-
data WellFormed t = Valid t
| Invalid
instance Monad WellFormed
where
(>>=) :: RefTy a => WellFormed a -> (a -> WellFormed b) -> WellFormed b
Valid t >>= f
| tyOK t = f t
| otherwise = Invalid
Invalid >>= _ = Invalid
-}
Which got me into the known problem of "restricted Monad". The suggested answer is to have the Wellformed
monad to be general but restrict the functions. However that would go back to adding the well-formed check everywhere. Is there a better way to get around?
回答1:
In your case, I don't think you actually want a monad, just the sugar that accompanies do
notation. For example, have you thought about what your definition of Applicative
will look like? Things get messy fast when you try to cheat your way through this.
Instead, if you want to use the do
-notation, I suggest you use
{-# LANGUAGE RebindableSyntax #-}
which allows you to redefine, amongst other thing, the (>>=)
and return
used in desugaring a do
block. You could then write something like:
myBind :: RefTy t1 => WellFormed t1 -> (t1 -> WellFormed t2) -> WellFormed t2
myBind Invalid _ = Invalid
myBind (Valid t) f | tyOK t = f t
| otherwise Invalid
myReturn :: WellFormed t
myReturn t = Valid t
I'm not sure I agree with those definitions, but regardless you would then be able to write something like
do
...
where (>>=) = myBind
return = myReturn
来源:https://stackoverflow.com/questions/38572799/using-a-monad-to-implicitly-check-refinement-type-well-formedness