Using a monad to implicitly check refinement type well-formedness

拜拜、爱过 提交于 2019-12-24 06:48:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!