gpt4 book ai didi

haskell - 带有 Either 的 Monadic 守卫

转载 作者:行者123 更新时间:2023-12-03 07:42:00 24 4
gpt4 key购买 nike

我正在 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"

考虑到这一点,如果我有几个守卫,缩进会太多,所以我更改了我的代码以使用 guard

我知道 guard 表达式的返回类型是 () 但在后台它使我的 Either monad 也失败了返回 Left ""。有什么方法可以将字符串传递给守卫?

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

最佳答案

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

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

关于haskell - 带有 Either 的 Monadic 守卫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35016694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com