{-# LANGUAGE RebindableSyntax, DeriveGeneric, DeriveFunctor, DeriveTraversable, DerivingVia, FlexibleInstances #-}
import Language.Stochaskell
stochaskell
Stochaskell, version 0.1.0 Copyright (C) 2015-2020 David A Roberts This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions; see the LICENSE for details. Using installation directory at /home/jovyan/stochaskell
import Language.Stochaskell.Expression
data Tree t
= Branch t t
| Leaf R
deriving (Show, Generic, Generic1, Functor, Foldable, Traversable)
deriving Show1 via (Generically1 Tree)
instance ExprType (Tree (FixE Tree))
instance Constructor (Tree (FixE Tree))
instance (ExprType t) => ExprType (Tree (Expression t))
instance (ExprType t) => Constructor (Tree (Expression t))
type T = FixE' Tree
production :: R -> P (Expression (Tree R))
production p = mixture'
[(p, do
return . fromConcrete $ Branch (p/2) (p/2))
,(1-p, do
x <- uniform 0 1
return . fromConcrete $ Leaf x)
]
pcfg :: P T
pcfg = unfoldP production 1
tree <- simulate pcfg
print tree
Branch (Fix (Branch (Fix (Leaf 0.4898595150062972)) (Fix (Branch (Fix (Leaf 0.2523685666712354)) (Fix (Leaf 0.631889727678022)))))) (Fix (Branch (Fix (Leaf 0.1620737376264192)) (Fix (Branch (Fix (Leaf 0.46874567676577183)) (Fix (Leaf 0.2778033925412521))))))
reduction :: Tree R -> P R
reduction (Branch a b) = do
return (a + b)
reduction (Leaf a) = do
b <- bernoulli (1/2)
return (if b then a else 0)
treeSubsetSum :: T -> P R
treeSubsetSum = foldP (fromCaseP' reduction)
simulate (treeSubsetSum tree)
0.958605191772069