首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一元守卫

一元守卫
EN

Stack Overflow用户
提问于 2016-01-26 22:50:59
回答 1查看 1.3K关注 0票数 3

我正在用Haskell实现一个类型检查器。类型检查函数的主要特征是

代码语言:javascript
复制
judge :: Term -> StateT Context (Either String) Type

如果类型检查器失败,则返回lift $ Left "Something went wrong"

例如,一个检查if (伪)类型的函数:

代码语言:javascript
复制
judge (ExpIf test cons alt) =
  do
    testT <- judge test
    consT <- judge cons
    altT  <- judge alt
    guard $ consT == altT

最初,这段代码是这样编写的。

代码语言:javascript
复制
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失败。有没有办法让我把字符串传给守卫?

代码语言:javascript
复制
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!"
EN

回答 1

Stack Overflow用户

发布于 2016-01-27 08:42:17

您可以将when/unlessfailthrowError结合使用(取决于您的monad对这些类多态函数的特定实现)。例如,您可以这样写:

代码语言:javascript
复制
unless (consT == altT) (throwError "types of cons and alt should match")
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35016694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档