haskell - 如何将 traverse 与 exceptT 和 List 一起使用,以便仅当所有项目都为 Left 时才返回 Left?

标签 haskell monads traversal monad-transformers

例如我有这个功能

foo :: Int -> ExceptT String (State Int) Int
foo x = if x == 0 then throwError "x == 0" else return x

如果我使用遍历

evalState (runExceptT $ traverse foo [0,1,2]) 0

返回

Left "x == 0"

但我想要正确的[1,2] 仅当所有列表项均为零时才返回 Left

最佳答案

这是一个关于 traverse 的问题,还是您只想收集不抛出异常的 foo 的结果?

后者的直接方法是在“try-catch” block 中运行 foo 的每次调用,该 block 返回 Maybe Int,然后 catMaybes 列表.

示例:

import Data.Maybe
import Control.Monad
import Control.Monad.Except
import Control.Monad.State

foo :: Int -> ExceptT String (State Int) Int
foo x = if x == 0 then throwError "x == 0" else return x

orNothing p = catchError (fmap return p) (\e -> return Nothing)

collectFoos xs = do ys <- fmap catMaybes $ mapM (orNothing . foo) xs
                    case ys of
                      [] -> throwError "no successful call to foo"
                      _  -> return ys

doit xs = runState (runExceptT (collectFoos xs)) 100

关于haskell - 如何将 traverse 与 exceptT 和 List 一起使用,以便仅当所有项目都为 Left 时才返回 Left?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37413623/

相关文章:

haskell - 是否有 F# 工具/库将值可视化为图形(如 Haskell 的 vacuum)?

scala - 取消选择已选择的选项

haskell - 作为 Monad 实例的函数

haskell - 在 Haskell 的绑定(bind)运算符中使用 return (>>=)

javascript - 如何遍历 HTML

scala - 如何从左到右和从右到左遍历数组?

algorithm - Excel VBA脚本优化——遍历算法——解决这个难题?

haskell - 非柯里化(Currying)函数

haskell - 对于具有嵌套 Maybe 值的 Tree 数据类型,Traversable 实例应该是什么样子?

haskell - 这些函数是尾递归的吗?