Skip to content

Instantly share code, notes, and snippets.

@wbadart
Last active April 13, 2020 17:08
Show Gist options
  • Save wbadart/f21db61e04ae9e4927f9eb6e5c9abd59 to your computer and use it in GitHub Desktop.
Save wbadart/f21db61e04ae9e4927f9eb6e5c9abd59 to your computer and use it in GitHub Desktop.
Probability newtype with smart constructor and unidirectional pattern example
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
{-# 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