Last active
April 13, 2020 17:08
-
-
Save wbadart/f21db61e04ae9e4927f9eb6e5c9abd59 to your computer and use it in GitHub Desktop.
Probability newtype with smart constructor and unidirectional pattern example
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
module Main where | |
import Data.Probability | |
main :: IO () | |
main = do | |
s <- readLn | |
case probability s of | |
-- This pattern match wouldn't work w/o PatternSynonyms | |
-- (you could still pattern match on the Maybe, but not on | |
-- the Probability) | |
Just (Probability p) -> putStrLn $ "Valid probability: " <> show p | |
Nothing -> putStrLn $ "Invalid probability: " <> show s |
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
{-# LANGUAGE PatternSynonyms #-} | |
module Data.Probability | |
( Probability -- note we do not export the data constructor 'UnsafeProbability' | |
, unwrap | |
, pattern Probability | |
, probability | |
) where | |
newtype Probability = UnsafeProbability { unwrap :: Double } deriving Show | |
pattern Probability p <- UnsafeProbability p | |
-- | 'Probability' "smart constructor" | |
probability :: Double -> Maybe Probability | |
probability p | 0 <= p && p <= 1 = Just (UnsafeProbability p) | |
| otherwise = Nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment