!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~       !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      Safe-Inferred*composition of a list of monadic functionslike  but returns all intermediate values like Control.Monad.HT.iterateLimit, but counts differently. Is it actually useful this way?8While loop with a posteriori check. Loops at least once.4While loop with a priori check. Can loop zero times. Safe-Inferred Safe-Inferred'A shape is a mapping from the interval [0,1] to non-negative numbers. They need not to be normalized (sum up to 1) because this is done by subsequent steps. (It would also be impossible to normalize the function in a way that each discretization is normalized as well.) Safe-Inferred Safe-Inferredfiltering distributions distribution generators Probability disributionThe underlying data structure is a list. Unfortunately we cannot use a more efficient data structure because the key type must be of class  , but the  class does not allow constraints for result types. The Monad instance is particularly useful because many generic monad functions make sense here, monad transformers can be used and the monadic design allows to simulate probabilistic games in an elegant manner.%We have the same problem like making Data.Set an instance of , see Lhttp://www.randomhacks.net/articles/2007/03/15/data-set-monad-haskell-macros@If you need efficiency, you should remove redundant elements by .  converts to l and back internally and you can hope that the compiler fuses the lists with the intermediate Map structure.#The defined monad is equivalent to WriterT (Product prob) [] a. See  Thttp://www.randomhacks.net/articles/2007/02/21/refactoring-probability-distributions.nCheck whether two distributions are equal when neglecting rounding errors. We do not want to put this into an [ instance, since it is not exact equivalence and it seems to be too easy to mix it up with liftM2 (==) x y.0can fail because of rounding errors, better use 3pretty printing#<Give a list of frequencies, they do not need to sum up to 1.)3extracting and mapping the domain of a distribution* with normalization+Funfold a distribution of distributions into one distribution, this is  with normalization.,conditional distribution.&conditional probability, identical to  / k in infix form. Can be considered an additional monadic combinator, which can be used where you would want !" otherwise.6selecting from distributions9expectation value:statistical analyses>.We would like to have an equality test of type +(==) :: T prob a -> T prob a -> T prob Boolthat is consistent with the  $ instance. We would certainly define !x==y = norm (liftM2 (==) x y) . However the  class enforces the type !T prob a -> T prob a -> Bool .^We could implement this as check for equal distributions. This would be inconsistent with the  s instance because it compares entire distributions, not only individual outcomes. Thus we provide this function as  .I would prefer to omit the , instance completely, but unfortunately the   instance requires  as superclass.=  !"#$%&'()*+,True False -./0123456789:;<=>?@AB6  !"#$%&'()*+,-./0123456789:;=  BA@?> =< !"#$%&'()*+,-./0123456789:;9   !"#$%&'()*+,-./0123456789:;<=>?@AB./8 Safe-InferredC<functions to convert a list of transitions into a transitionD8functions to convert a list of changes into a transitionEprobabilistic generatorFdeterministic generatorHH; maps a change function to the result of a transformation (H is somehow a lifted form of *) The restricted type of f, results from the fact that the argument to t cannot be changed to b in the result E type.I8unfold a distribution of transitions into one transition2NOTE: The argument transitions must be independentJ&Composition of transitions similar to #- but with intermediate duplicate elimination.LIn fix $ go a -> do ...; go xy any action after a go is ignored.CDEFGHIJKLMNOPQRSTUVWXYZCDEFGHIJKLMNOPQRSTUVWXYZFEGHIJKLDMNOPQRSTCUVWXYZCDEFGHIJKLMNOPQRSTUVWXYZ Safe-Inferred[%calculate the full joint distributionfprior burglary 1%gprior earthquake 0.1%h>conditional probability of alarm given burglary and earthquakei3conditional probability of john calling given alarmj3conditional probability of mary calling given alarml>what is the probability that mary calls given that john calls?[\]^_`abcdefghijkl[\]^_`abcdefghijkldcbefghij[\]^_`akl [\]^_`abcdefghijkl Safe-Inferredm"Two possible causes for one effectmnopqrstuvwxyz{|}~mnopqrstuvwxyz{|}~vutsrqwxyz{mpon|}~mponqrstuvwxyz{|}~ Safe-Inferred  Safe-InferredAlternative way for computing the distribution. It is usually more efficient because we do not need to switch on the healthy state.  Safe-Inferred$product of independent distributions sixes p n. computes the probability of getting p sixes (>1, ==2, ...) when rolling n dice  Safe-Inferred&only boys in a family that has one boy  Safe-Inferred$ Safe-Inferred!"#$%&'()*+,-./012!"#$%&'()*+,-./01!"#$%&'()*+,-./012  Safe-Inferredrandom transition random changeRandomized distribution Random valuesRun random action in 3 monad.Run random action without 3 using a seed.o converts a list of randomly generated values into a distribution by taking equal weights for all values. Thus dist (replicate n rnd) simulates rnd nD times and returns an estimation of the distribution represented by rnd.  Safe-Inferred<walk is a bounded version of the predefined function iterate converts a list of 4s into a list of randomized distributions, i.e., an P, by creating a randomized distribution for each list position across all traces  Safe-Inferred8Print distribution as table with configurable precision. Safe-Inferredstatistical analyses  Safe-InferredSimulation means to repeat a Rnd.change change many times and to accumulate all results into a distribution. Therefore, simulation can be regarded as an approximation of distributions through randomization.The Sim class allows the overloading of simulation for different kinds of generators, namely transitions and Rnd.change changes: (Trans a = a -> Dist a ==> c = Dist .RChange a = a -> Rnd.T a ==> c = Rnd.T = IO'returns the final randomized transition/returns the whole trace for a k-fold simulation/returns the whole trace for a single simulation Safe-Inferred(initial configuration of the game statusSteps of the game: hide the prize choose a door-open a non-open door, not revealing the prizeapply strategy: switch or stay                        5Multi-parameter type class with functional dependency Safe-Inferred2468*<Give a list of frequencies, they do not need to sum up to 1. !"#$%&'()*+,- !"#$%&'()* "#-,+!$%&'()* !"#$%&'()*+,- Safe-Inferred31(customers waiting,validity period of that queue)4,customers and their individual serving times6(servingTime, nextArrival):multiple servers;<decrease served customers remaining time by specified amount<time until next completion./0123456789:;<=>?@ABCDEFGHIJK./0123456789:;<=>?@ABCDEFGHIJK765432189:;<=0/.>?@ABCDEFGHIJK./0123456789:;<=>?@ABCDEFGHIJK Safe-InferredZavg barber idle time[.avg customer waiting time (unserved customers)LMNOPQRSTUVWXYZ[LMNOPQRSTUVWXYZ[PQRSTUVWLONMXYZ[ LONMPQRSTUVWXYZ[ Safe-Inferred}mini-blackjack: draw 2 cards, and if value is less than 14, continue drawing until value equals or exceeds 14. if values exceeds 21, you lose, otherwise you win.(\]^_`abcdefghijklmnopqrstuvwxyz{|}~(\]^_`abcdefghijklmnopqrstuvwxyz{|}~(mlnopqhkjirstucgfed]ba`_^\vwxyz{|}~\]ba`_^cgfedhkjilmnopqrstuvwxyz{|}~ Safe-Inferredoptimal strategyFdistribution of the scores that are achieved with the optimal strategy Safe-Inferred<We reformulate the problem to the following game: There are two players, both of them collect a number of points. In every round the player with the smaller score throws a die and adds the pips to his score. If the two players somewhen get the same score, then the game ends and the score is the result of the game ( Just score\). If one of the players exceeds the maximum score n, then the game stops and players lose (Nothing).bThis version could be generalized to both Random and Distribution monad while remaining efficient.In  we group the scores by rounds. This leads to a growing probability distribution, but we do not need the round number. We could process the game in a different way: We only consider the game states where the lower score matches the round number. can be written in terms of a matrix power. For n pips we need a n n matrix. Using symmetries, we reduce it to a square matrix with size n(n+1)/2. p[n+1,(n+1,n+1)]  p[n,(n+0,n+0)] | p[n+1,(n+1,n+2)] | | p[n,(n+0,n+1)] | | p[n+1,(n+1,n+3)] | | p[n,(n+0,n+2)] | | ... | | ... | | p[n+1,(n+1,n+6)] | = M/6 | p[n,(n+0,n+5)] | | p[n+1,(n+2,n+2)] | | p[n,(n+1,n+1)] | | ... | | ... | | p[n+1,(n+2,n+6)] | | p[n,(n+1,n+5)] | | ... | | ... | p[n+1,(n+6,n+6)]  p[n,(n+5,n+5)] M[(n+1,(x,y)),(n,(x,y))] = 62M[(n+1,(min y (n+d), max y (n+d))), (n,(n,y))] = 1 M[(n+1,(x1,y1)),(n,(x0,y0))] = 0OThis is a bruteforce implementation of the original game: We just roll the die maxScoreE times and then jump from die to die according to the number of pips. Safe-Inferred Visualization outputsettings for individual plotsglobal settings for one figure'default settings for figure environmentdefault plotting environment!create a plot from a distributioncreate a plot from a functioncreate a plot from a listGwe want to increase the bounds absolutely, account for negative numbersGwe want to increase the bounds absolutely, account for negative numbers?=? Safe-Inferred     Safe-InferredBtree growth simulation: start with seed and run for n generationstree n( : tree distribution after n generationshist n2 : history of tree distributions for n generations[Since '(*.)' is overloaded for Trans and RChange, we can run the simulation ~. directly to  n *. live.                    4%&'()*+,-.%/0123456789:;<=>?@ABCDEFGH&'()IJKLMNOPQRS TUVWXYZ[\]^_`abc%deJK#fghi7'&)FGjklmnopqrstuvwxyz{|}~qx{xxx   x   d  % / 0 P Q ` _ a                .  % / [ \ ^XYZqE.H&'()FG     1 !"#$%&'()*+,-./0123456789:;<=>?@ABqCDxEFGHRIJKLMNOPQRSTUVWXYZ[\]^[x_`abcdefghijklmnopqrsttuvwxyz{|}~{#!$$$$$$$$$$$$$$$$$$probability-0.2.5Numeric.Probability.Shape Numeric.Probability.DistributionNumeric.Probability.Transition!Numeric.Probability.Example.Alarm$Numeric.Probability.Example.Bayesian Numeric.Probability.Example.Boys%Numeric.Probability.Example.Diagnosis Numeric.Probability.Example.Dice!Numeric.Probability.Example.NBoys&Numeric.Probability.Example.ProfessionNumeric.Probability.RandomNumeric.Probability.TraceNumeric.Probability.PercentageNumeric.Probability.ExpectationNumeric.Probability.Simulation%Numeric.Probability.Example.MontyHallNumeric.Probability.Object#Numeric.Probability.Example.Queuing"Numeric.Probability.Example.Barber&Numeric.Probability.Example.Collection%Numeric.Probability.Example.DiceAccum#Numeric.Probability.Example.KruskalNumeric.Probability.Visualize$Numeric.Probability.Example.Predator&Numeric.Probability.Example.TreeGrowthNumeric.Probability.MonadNumeric.Probability.EitherNumeric.Probability.ShowDataMapDistfilter Control.MonadguardcomposeNumeric.Probability.PrintListTlinearuniformnegExpnormal normalCurveSelectOtherCaseSpreadConsdeconsEventoneOfjust certainly errorMarginapproxliftsizecheckconssumPsortP sortPDescsortElemnormnorm'norm''pretty//%equalchooseenumrelativeshapeextractmapunfoldcondtruth?=<<>>=?abovebelowselect fromFreqsmapMaybeselectPscanP??expectedvariancestdDev $fFractionalT$fNumT$fEqT$fShowT $fFunctorT$fApplicativeT$fMonadTSpreadTSpreadCChangeid untilLeftfixapplymaybeliftTuniformTlinearTnormalTenumT relativeTBurglaryBburglary earthquakealarmjohnmaryPBool ProbabilityflpbeajmbJointpmjNodesEASPredSTransPStateStateeventhappensnetworksourcebingaEbEFamilyChildGirlBoybirthfamilyallBoys existsBoy familyWithBoytwoBoyscountBoy countBoysnumBoysFindingPositiveNegativeIllHealthypDiseasepFalseNegativepFalsePositivedistdistAltpDiedietwoDicedicetwoSixessixesdrollg3addTwoboysnBoys onlyBoys1correctAnswers categories ApproxDist Transition DistributionrandomRrunrunSeedprintpickchangeRExpandRSpaceRWalkRTraceExpandSpaceWalkTracewalkmerge zipListWithRTransTransRDistpercentshowPfixroundRel////*liftPliftP2 $fRandomT $fFloatingTExpected FromFloat fromFloatToFloattoFloat floatDist $fExpectedT $fExpected[]$fExpectedInteger $fExpectedInt$fExpectedFloat$fFromFloatInteger$fFromFloatInt$fFromFloatFloat $fToFloatT$fToFloatInteger $fToFloatInt$fToFloatFloatC~.~..~*.$fCT$fCT0 StrategyMOutcomeLoseWinStrategyDoorsprizechosenopenedDoordoorsstarthideopenswitchstaygameresultevalsimEval firstChoiceswitch'stayMswitchMevalMfromFrequencies$fCprobEitherT$fCprobT $fCDoubleTREventsREventRProfileEventsSystemQueueProfileTimesystemmEventmServe mTimeStepmSystemrSystem rBuildEventsrmSystem evalSystemunitmaxQueue allWaiting countWaitingwaitinginSystemtotalserveridleidleAvgPCategory MoreThanTen FourToTen ThreeOrLesscustServnextCustbarbers customersruns barberEvent barberEvents barberSystemcatperc barberIdle customerWaitCardRankAceKingQueenJackPlainSuitDiamondHeartSpadeClubMarbleGR Collection selectOneselect1select2bucketjarpRGBpRGplainsfacesisFaceisPlainrankssuitsdeckvalue totalValuedrawdrawFdrawTo16win chanceWinScorerollcontinuestrategy gameRoundgameFastgameFastEither gameFastFixgameLeastScoreflattenedMatrix startVector compareMaybecumulaterunExacttracechopmeeting bruteforce runSimulationlatexDielatexMarkedDielatexFromChainlatexChoppedFromChain makeChainsVisPlotysxscolor lineStyle lineWidthlabelPlotFun LineStyleTwoDashLongDashDotDashDottedDashedSolidColorCustomWhiteYellowOrangeMagenta LightGreenCyanDarkGrayPurpleGrayBrownRedGreenBlueBlack FigureEnvFEfileNametitlexLabelyLabelfigureplotcolorssetColor autoColorplotDplotRDplotFplotLplotRLyls metaTupleincrdecrfigfigP showParamslegenddrawyvecout0out1$fShowLineStyle $fShowColordsv0p0dvdpdvpvpvspsfig1TreeFallenHitAliveHeightgrowhitfallevolveseedtreehistsimTreesimHistt2h2st2sh2heightp1p2p3p4 heightAtTimep5 heightCurvep6doneev5iteratedoWhilewhile whileTraceEitherTthrow$fMonadEitherT$fApplicativeEitherT$fFunctorEitherTshowRghc-prim GHC.ClassesOrdbaseGHC.BaseMonadEqfmapjoinGHC.NumNumLinesasLinesshowNQindent printListasTupleasSeqasListasSetasLispasPlainasPlain'asStringasCasesasDefs asParagraphs $fShowLines GHC.TypesIO