Created
March 24, 2017 23:48
-
-
Save MichaelXavier/0812475306ed61ae361d04a1c3af699c to your computer and use it in GitHub Desktop.
a thing like a prism but non-composable and has error types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Lens | |
-- from Control.Error | |
hush :: Either e a -> Maybe a | |
hush (Left _) = Nothing | |
hush (Right a) = Just a | |
------------------------------------------------------------------------------- | |
data Lossy e a b = Lossy { | |
previewE :: a -> Either e b | |
, reviewE :: b -> a | |
} | |
lossy :: (b -> a) -> (a -> Either e b)-> Lossy e a b | |
lossy = flip Lossy | |
hushLossy :: Lossy e a b -> Prism' a b | |
hushLossy l = prism' (reviewE l) (hush . (previewE l)) | |
------------------------------------------------------------------------------- | |
newtype MyInt = MyInt Int deriving (Show) | |
data MyIntError = TooBig | |
| TooSmall | |
deriving (Show) | |
myIntLossy :: Lossy MyIntError Int MyInt | |
myIntLossy = lossy toI fromI | |
where | |
toI (MyInt i) = i | |
fromI i | |
| i < 0 = Left TooSmall | |
| i > 10 = Left TooBig | |
| otherwise = Right (MyInt i) | |
useLikePrism :: Either MyIntError MyInt | |
useLikePrism = previewE myIntLossy 42 | |
useAsPrism :: Maybe MyInt | |
useAsPrism = 42 ^? hushLossy myIntLossy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment