Haskell 中的“guard”(而不是“guard”)可以用来为“Left”指定特定消息吗

问题描述 投票:0回答:1

如果

guard
-Monad 失败,RIO-Prelude 中的
Either
函数是否提供任何方法来决定消息的内容?这样例如

somefun :: Either String Int
somefun =  do guard (4+2 == 8); return 2

将返回

Left someContent
,而不是其中
someContent
是以某种方式指定给
guard
的字符串。

我无法根据文档找到任何方法,但如果它存在,我会很高兴知道它,因为

guard
可能是避免嵌套
if
语句的好方法。

haskell types functional-programming monads
1个回答
0
投票

guard
empty
一起使用,以防条件失败,所以不会。您应该使用
fail
来代替,从而制作一些允许添加失败消息的
guard

因此您可以使用:

guard' :: MonadFail m => String -> Bool -> m ()
guard' msg = go
  where go False = fail msg
        go True = pure ()

那么你就会失败:

somefun :: Either String Int
somefun =  do guard' "arithmetic error" (4+2 == 8); return 2
© www.soinside.com 2019 - 2024. All rights reserved.