right' ≡ dimap swapE swapE . left' where swapE :: Either a b -> Either b a swapE = either Right Left rmap Right ≡ lmap Right . right' lmap (left f) . right' ≡ rmap (left f) . right' right' . right' ≡ dimap unassocE assocE . right' where assocE :: Either (Either a b) c -> Either a (Either b c) assocE (Left (Left a)) = Left a assocE (Left (Right b)) = Right (Left b) assocE (Right c) = Right (Right c) unassocE :: Either a (Either b c) -> Either (Either a b) c unassocE (Left a) = Left (Left a) unassocE (Right (Left b)) = Left (Right b) unassocE (Right (Right c)) = Right c
rightToMaybe ≡ either (const Nothing) JustUsing Control.Lens:
rightToMaybe ≡ preview _Right rightToMaybe x ≡ x^?_Right
>>> rightToMaybe (Left 12) Nothing
>>> rightToMaybe (Right 12) Just 12
>>> fromRight 1 (Right 3) 3 >>> fromRight 1 (Left "foo") 1
fromRight' x ≡ x^?!_Right
>>> fromRight' (Right 12) 12
>>> isRight (Left "foo") False >>> isRight (Right 3) TrueAssuming a Left value signifies some sort of error, we can use isRight to write a very simple reporting function that only outputs "SUCCESS" when a computation has succeeded. This example shows how isRight might be used to avoid pattern matching when one does not care about the value contained in the constructor:
>>> import Control.Monad ( when ) >>> let report e = when (isRight e) $ putStrLn "SUCCESS" >>> report (Left "parse error") >>> report (Right 1) SUCCESS
unright ≡ unleft . dimap swapE swapE where swapE :: Either a b -> Either b a swapE = either Right Left rmap (either absurd id) ≡ unright . lmap (either absurd id) unsecond . rmap (first f) ≡ unsecond . lmap (first f) unright . unright ≡ unright . dimap unassocE assocE where assocE :: Either (Either a b) c -> Either a (Either b c) assocE (Left (Left a)) = Left a assocE (Left (Right b)) = Right (Left b) assocE (Right c) = Right (Right c) unassocE :: Either a (Either b c) -> Either (Either a b) c unassocE (Left a) = Left (Left a) unassocE (Right (Left b)) = Left (Right b) unassocE (Right (Right c)) = Right c
whenRight ≡ forM_Using Control.Lens:
whenRight ≡ forOf_ _Right
>>> whenRight (Right 12) print 12