-
Notifications
You must be signed in to change notification settings - Fork 0
/
Subdistribution.hs
66 lines (49 loc) · 1.93 KB
/
Subdistribution.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
{-# LANGUAGE RebindableSyntax #-}
module Subdistribution where
import Prelude hiding ((>>=), return)
import Data.Finitary
import Data.Ord
import Data.Maybe
import Data.List ( maximumBy )
import GHC.Generics (Generic)
import SubdistributionAux
data Distribution a where
Distribution :: (Eq a) => [(a, Rational)] -> Distribution a
unDistribution :: Distribution a -> [(a, Rational)]
unDistribution (Distribution d) = d
validity :: Distribution a -> Rational
validity (Distribution l) = totalWeight l
instance (Eq a) => Eq (Distribution a) where
(==) :: Distribution a -> Distribution a -> Bool
(==) (Distribution u) (Distribution v) =
isJust $ checkMaybe (reweight u) (reweight v)
(>>=) :: (Eq a, Eq b) => Distribution a -> (a -> Distribution b) -> Distribution b
(>>=) (Distribution d) f = Distribution $ distBind d (unDistribution . f)
(>>) :: (Eq a, Eq b) =>
Distribution a -> Distribution b -> Distribution b
(>>) d f = d >>= const f
return :: (Eq a) => a -> Distribution a
return x = Distribution [(x,1)]
observe :: Bool -> Distribution ()
observe True = return ()
observe False = absurd
assert :: Bool -> Distribution ()
assert = observe
absurd :: (Finitary a) => Distribution a
absurd = Distribution []
fromList, distribution :: (Eq a) => [(a,Rational)] -> Distribution a
fromList = Distribution . condense
distribution = fromList
toList :: (Eq a) => Distribution a -> [(a,Rational)]
toList = unDistribution
instance (Eq a, Show a) => Show (Distribution a) where
show :: Eq a => Distribution a -> String
show = showDistribution
showDistribution :: (Eq a, Show a) => Distribution a -> String
showDistribution d =
"Validity: " ++ show (validity d) ++ "\n" ++
"Posterior: " ++ show (unDistribution (normalize d)) ++ "\n"
normalize :: Distribution a -> Distribution a
normalize (Distribution x) = Distribution (distNormalize x)
uniform :: (Eq a) => [a] -> Distribution a
uniform l = fromList (map (, 1 / toRational (length l)) l)