簡體   English   中英

在Haskell中編寫firstRightOrLefts的慣用法?

[英]Idiomatic way to write firstRightOrLefts in Haskell?

我有以下方法:

firstRightOrLefts :: [Either b a] -> Either [b] a
firstRightOrLefts eithers = 
   case partitionEithers eithers of
      (_,  (x : _)) -> Right x
      (xs, _)       -> Left xs

困擾我的是丑陋的模式匹配,我想知道是否有更慣用的方法來編寫這種方法。 我的想法是,我有一堆可以返回Eithers的計算,我只想獲得第一個結果或所有錯誤消息。 也許我使用了錯誤的數據結構。 也許Writer monad會更適合這項任務。 我現在真的不確定。 歡呼任何幫助!

反向約定實際上只是Either的monad定義, sequence的定義就足夠了:

ghci> :t sequence :: [Either a b] -> Either a [b]
sequence :: [Either a b] -> Either a [b]
  :: [Either a b] -> Either a [b]

要將此實際應用於您的案例,我們需要一個函數flipEither:

firstRightOrLefts = fe . sequence . map fe
    where fe (Left a) = Right a
          fe (Right b) = Left b

MonadPlus例如Except有此行為:

import Control.Monad
import Control.Monad.Trans.Except

firstRightOrLefts :: [Either e a] -> Either [e] a
firstRightOrLefts = runExcept . msum . fmap (withExcept (:[]) . except)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM