Mapping over Either's Left

前端 未结 4 1676
慢半拍i
慢半拍i 2021-02-02 11:48

Somewhere in my app I receive an Either ParserError MyParseResult from Parsec. Downstream this result gets some other parsing done over using other libs. During tha

相关标签:
4条回答
  • 2021-02-02 11:48

    Another simple option is mapLeft in Data.Either.Combinators:

    mapLeft :: (a -> c) -> Either a b -> Either c b
    
    0 讨论(0)
  • 2021-02-02 11:55

    This can be done easily with lens:

    import Control.Lens
    
    over _Left (+1) $ Left 10   => Left 11
    over _Left (+1) $ Right 10  => Right 10
    over _Right (+1) $ Right 10 => Right 11
    
    0 讨论(0)
  • 2021-02-02 12:04

    We have such a function in the standard libraries,

    Control.Arrow.left :: a b c -> a (Either b d) (Either c d)
    

    is the generalisation to arbitrary Arrows. Substitute (->) for a and apply it infix, to get the specialisation

    left :: (b -> c) -> Either b d -> Either c d
    

    There is nothing wrong with your approach in principle, it's a sensible way to handle the situation.

    0 讨论(0)
  • 2021-02-02 12:14

    Another option is to use Bifunctor instance of Either. Then you have

    first :: (a -> b) -> Either a c -> Either b c
    

    (Also Bifunctor can be used to traverse over the first part of (a,b).)

    0 讨论(0)
提交回复
热议问题