我正在用Haskell实现一个类型检查器。类型检查函数的主要特征是
judge :: Term -> StateT Context (Either String) Type如果类型检查器失败,则返回lift $ Left "Something went wrong"。
例如,一个检查if (伪)类型的函数:
judge (ExpIf test cons alt) =
do
testT <- judge test
consT <- judge cons
altT <- judge alt
guard $ consT == altT最初,这段代码是这样编写的。
judge (ExpIf test cons alt) =
do
testT <- judge test
consT <- judge cons
altT <- judge alt
if altT == consT
then return consT
else lift $ Left "Types for cons and alt do not match"考虑到这一点,如果我有几个守卫,我会有太多的延迟,所以我更改了我的代码以使用guards。
我知道guard表达式的返回类型是(),但在后台,它返回Left ""也会使我的Either monad失败。有没有办法让我把字符串传给守卫?
judge (ExpIf test cons alt) =
do
testT <- judge test
consT <- judge cons
altT <- judge alt
guard (consT == altT) "types of cons and alt should match!"发布于 2016-01-27 08:42:17
您可以将when/unless与fail或throwError结合使用(取决于您的monad对这些类多态函数的特定实现)。例如,您可以这样写:
unless (consT == altT) (throwError "types of cons and alt should match")https://stackoverflow.com/questions/35016694
复制相似问题