Created
February 15, 2016 21:39
-
-
Save jtobin/f54e2173314ed7a76312 to your computer and use it in GitHub Desktop.
Independence and Applicativeness
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 DeriveFunctor #-} | |
{-# LANGUAGE LambdaCase #-} | |
import Control.Applicative.Free | |
import Control.Monad | |
import Control.Monad.Free | |
import Control.Monad.Primitive | |
import System.Random.MWC.Probability (Prob) | |
import qualified System.Random.MWC.Probability as MWC | |
data ProbF r = | |
BetaF Double Double (Double -> r) | |
| BernoulliF Double (Bool -> r) | |
deriving Functor | |
type Model = Free ProbF | |
type Sample = Ap Model | |
beta :: Double -> Double -> Model Double | |
beta a b = liftF (BetaF a b id) | |
bernoulli :: Double -> Model Bool | |
bernoulli p = liftF (BernoulliF p id) | |
coin :: Double -> Double -> Model Bool | |
coin a b = beta a b >>= bernoulli | |
eval :: PrimMonad m => Model a -> Prob m a | |
eval = iterM $ \case | |
BetaF a b k -> MWC.beta a b >>= k | |
BernoulliF p k -> MWC.bernoulli p >>= k | |
independent :: f a -> Ap f a | |
independent = liftAp | |
evalIndependent :: PrimMonad m => Sample a -> Prob m a | |
evalIndependent = runAp eval | |
sample :: Sample a -> IO a | |
sample model = MWC.withSystemRandom . MWC.asGenIO $ | |
MWC.sample (evalIndependent model) | |
flips :: Sample (Bool, Bool) | |
flips = (,) <$> independent (coin 1 8) <*> independent (coin 8 1) | |
@sth4nth you can find the implementation of that article at https://github.com/adscib/monad-bayes
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you give some comment on this paper?
Adam Ścibior, Zoubin Ghahramani, and Andrew D. Gordon. Practical probabilistic programming with monads.