Skip to content

Instantly share code, notes, and snippets.

@MichaelXavier
Created March 24, 2017 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelXavier/0812475306ed61ae361d04a1c3af699c to your computer and use it in GitHub Desktop.
Save MichaelXavier/0812475306ed61ae361d04a1c3af699c to your computer and use it in GitHub Desktop.
a thing like a prism but non-composable and has error types
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