单身守卫与 [英] Monadic guard with Either

查看:124
本文介绍了单身守卫与的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Haskell中实现一个类型检查器。类型检查功能的主要签名是

  judge :: Term  - > StateT上下文(任意字符串)类型

如果类型检查器失败,则返回 lift $ left发生错误



例如,一个函数来键入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< ; - 判断测试
consT< - 判断cons
altT< - 判断alt
如果altT == consT
然后返回consT
else lift $ Left类型对于cons和alt不匹配

鉴于,如果我有几个守卫,我会有太多的侮辱,所以我改变了我的代码使用 guard s。



我知道返回类型的瓜尔d 表达式是(),但在后台,它使我的或者 monad失败通过返回 Left。有没有什么办法可以传递一个字符串给守卫?

  judge(ExpIf test cons alt)= 
do
testT< - 判断测试
consT< - 判断cons
altT< - 判断alt
guard(consT == altT)cons和alt的类型应该匹配!


解决方案

您可以将 / code> / 除非失败 throwError (取决于你的monad对这些类多态函数的具体实现)。例如,您可以写:

 除非(consT == altT)(throwErrorcons和alt的类型应该匹配) 


I am implementing an typechecker in Haskell. The main signature of typechecking functions is

judge :: Term -> StateT Context (Either String) Type

If the typechecker fails, it returns lift $ Left "Something went wrong".

For example, a function to typecheck an if (pseudo):

judge (ExpIf test cons alt) =
  do
    testT <- judge test
    consT <- judge cons
    altT  <- judge alt
    guard $ consT == altT

Originally this code was written as follows.

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"

Given that, if I have a few guards, I would have too much indendation so I changed my code to use guards.

I know that the return type of the guard expression is () but in the background it makes my Either monad fail as well by returning Left "". Is there any way I could pass a string to the guard?

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!"

解决方案

You can combine when/unless with either fail or throwError (depending on your monad's particular implementation of these class-polymorphic functions). For example, you might write:

unless (consT == altT) (throwError "types of cons and alt should match")

这篇关于单身守卫与的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆