!@      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~       !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?Safe@ABSafe#C probability*composition of a list of monadic functionsD probabilitylike E but returns all intermediate values like Control.Monad.HT.iterateLimit, but counts differently. Is it actually useful this way?F probability8While loop with a posteriori check. Loops at least once.G probability4While loop with a priori check. Can loop zero times.CEDFGHSafe#mIJKLMNOPQRSTUVWXYSafe(Y probability'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(ZSafeQ probabilityfiltering distributions  probabilitydistribution generators  probabilityProbability 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. probabilitynCheck 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. probability0can fail because of rounding errors, better use 3 probabilitypretty printing# probability<Give a list of frequencies, they do not need to sum up to 1.) probability3extracting and mapping the domain of a distribution* probability^ with normalization+ probabilityFunfold a distribution of distributions into one distribution, this is _ with normalization., probabilityconditional distribution. probability&conditional probability, identical to  !/ probability !k in infix form. Can be considered an additional monadic combinator, which can be used where you would want "# otherwise.6 probabilityselecting from distributions9 probabilityexpectation value: probabilitystatistical analyses> probability.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., probabilityTrue  probabilityFalse 6  !"#$%&'()*+,-./0123456789:;6   !"#$%&'()*+,-./0123456789:;0.1/181SafeT FGHIGFHISafeVN probability$product of independent distributionsQ probability sixes p n. computes the probability of getting p sixes (>1, ==2, ...) when rolling n dice JKLMNOPQRST LKJMNOPQRSTSafeYa probabilityAlternative way for computing the distribution. It is usually more efficient because we do not need to switch on the healthy state.UWVXZY[\]^_`ab\[XZYUWV]^_`abSafeZDklnmopqrstuvwxypolnmkqrstuvwxySafe[ probability&only boys in a family that has one boy}~}~Safeb\ probability%calculate the full joint distribution probabilityprior burglary 1% probabilityprior earthquake 0.1% probability>conditional probability of alarm given burglary and earthquake probability3conditional probability of john calling given alarm probability3conditional probability of mary calling given alarm probability>what is the probability that mary calls given that john calls? Safen probability<functions to convert a list of transitions into a transition probability8functions to convert a list of changes into a transition probabilityprobabilistic generator probabilitydeterministic generator probability; maps a change function to the result of a transformation ( 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  type. probability8unfold a distribution of transitions into one transition2NOTE: The argument transitions must be independent probability&Composition of transitions similar to $- but with intermediate duplicate elimination. probabilityIn fix $ go a -> do ...; go xy any action after a go is ignored. Safew probabilityrandom transition probability random change probabilityRandomized distribution probability Random values probabilityRun random action in a monad. probabilityRun random action without a using a seed. probabilityo 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{ probability<walk is a bounded version of the predefined function iterate probability 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 probabilitySimulation 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 probability'returns the final randomized transition probability/returns the whole trace for a k-fold simulation probability/returns the whole trace for a single simulation668 SafeF probability8Print distribution as table with configurable precision.0Safe probabilitystatistical analyses 5Multi-parameter type class with functional dependencySafe=?@ACN  probability<Give a list of frequencies, they do not need to sum up to 1.         Safe probability1(customers waiting,validity period of that queue) probability,customers and their individual serving times probability(servingTime, nextArrival) probabilitymultiple servers probability<decrease served customers remaining time by specified amount probabilitytime until next completion !"#$%&'()*+,- !"#$%&'()*+,-Safe&< probabilityavg barber idle time= probability.avg customer waiting time (unserved customers).10/23456789:;<=23456789.10/:;<=Safeb probabilitymini-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.(ABGFEDCHLKJIMOPNQRSTUVWXYZ[\]^_`abcdefgh(RQSTUVMOPNWXYZHLKJIBGFEDCA[\]^_`abcdefghSafe  probability(initial configuration of the game status probabilitySteps of the game: hide the prize choose a door-open a non-open door, not revealing the prizeapply strategy: switch or staystvuwxy|{z}~}~xy|{zwtvusSafe probability<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). probabilitybThis version could be generalized to both Random and Distribution monad while remaining efficient. probabilityIn  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. probability 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))] = 0 probabilityOThis 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.Safei probabilityoptimal strategy probabilityFdistribution of the scores that are achieved with the optimal strategySafe probability"Two possible causes for one effectSafe[  probabilityVisualization output probabilitysettings for individual plots probabilityglobal settings for one figure probability'default settings for figure environment probabilitydefault plotting environment probability!create a plot from a distribution probabilitycreate a plot from a function probabilitycreate a plot from a list probabilityGwe want to increase the bounds absolutely, account for negative numbers probabilityGwe want to increase the bounds absolutely, account for negative numbers=     =     Safe˔ probabilityBtree growth simulation: start with seed and run for n generations probabilitytree n( : tree distribution after n generations probabilityhist n2 : history of tree distributions for n generations probability[Since '(*.)' is overloaded for Trans and RChange, we can run the simulation ~. directly to  n *. live. !"#$%&'()*+,-./ !"$#%&'()+-*,./Safe̲ 3456789:;<=>? 3456789:;<=>?b%&'()*+,-.%/0123456789:;<=>?@ABCDEFGH&'()IJKLMNOPQRS!TUVWXYZ[\]^_`abcd efg ehijklmnopqrstuv ewxyz{|}~ e e   %  J K $ 7 ' & ) F G     % / 0 P Q z ` _ a                 .  % / [ \ ^ ] XYZ.H&'()FGt1      !"#$%&'()*+,-./0123e4567R89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXtYZ[\]^_`aEbcdefghijklmnop}~qrst ehieuvwxyz{|}~tie^t e$       !"#$!"%!"&!'()*+(probability-0.2.6-FCfL4C1csNiGopwqk8oMyUNumeric.Probability.Shape Numeric.Probability.Distribution&Numeric.Probability.Example.Profession Numeric.Probability.Example.Dice%Numeric.Probability.Example.Diagnosis Numeric.Probability.Example.Boys!Numeric.Probability.Example.NBoys!Numeric.Probability.Example.AlarmNumeric.Probability.TransitionNumeric.Probability.RandomNumeric.Probability.TraceNumeric.Probability.SimulationNumeric.Probability.PercentageNumeric.Probability.ExpectationNumeric.Probability.Object#Numeric.Probability.Example.Queuing"Numeric.Probability.Example.Barber&Numeric.Probability.Example.Collection%Numeric.Probability.Example.MontyHall#Numeric.Probability.Example.Kruskal%Numeric.Probability.Example.DiceAccum$Numeric.Probability.Example.BayesianNumeric.Probability.Visualize&Numeric.Probability.Example.TreeGrowth$Numeric.Probability.Example.PredatorNumeric.Probability.EitherNumeric.Probability.MonadNumeric.Probability.PrintListNumeric.Probability.ShowDataMapDistfilter Control.MonadguardcomposeTlinearuniformnegExpnormal normalCurveSelectCaseOtherSpreadConsdeconsEventoneOfjust certainly errorMarginapproxliftsizecheckconssumPsortP sortPDescsortElemnormnorm'norm''pretty//%equalchooseenumrelativeshapeextractmapunfoldcondtruth?=<<>>=?abovebelowselect fromFreqsmapMaybeselectPscanP??expectedvariancestdDev $fFractionalT$fNumT$fEqT$fShowT $fFunctorT$fApplicativeT$fMonadT $fEqSelect $fOrdSelect $fShowSelect ProbabilitycorrectAnswers categoriesDiedietwoDicedicetwoSixessixesdrollg3addTwoFindingNegativePositiveStateHealthyIllpDiseasepFalseNegativepFalsePositivedistdistAltp $fEqState $fOrdState $fShowState $fEnumState $fEqFinding $fOrdFinding $fShowFinding $fEnumFindingFamilyChildBoyGirlbirthfamilyallBoys existsBoy familyWithBoytwoBoyscountBoy countBoysnumBoys $fEqChild $fOrdChild $fShowChildboysnBoys onlyBoys1BurglaryBburglary earthquakealarmjohnmaryPBoolflpbeajmbJointpmj $fEqBurglary $fOrdBurglary$fShowBurglarySpreadTSpreadCChangeid untilLeftfixapplymaybeliftTuniformTlinearTnormalTenumT relativeT ApproxDist Transition DistributionrandomRrunrunSeedprintpickchangeRExpandRSpaceRWalkRTraceExpandSpaceWalkTracewalkmerge zipListWithC~.~..~*.$fCT$fCT0RTransTransRDistpercentshowPfixroundRel////*liftPliftP2 $fRandomT $fFloatingT$fOrdTExpected FromFloat fromFloatToFloattoFloat floatDist $fToFloatT$fToFloatInteger $fToFloatInt$fToFloatFloat$fFromFloatInteger$fFromFloatInt$fFromFloatFloat $fExpectedT $fExpected[]$fExpectedInteger $fExpectedInt$fExpectedFloatfromFrequencies$fCprobEitherT$fCprobT $fCDoubleTREventsREventRProfileEventsSystemQueueProfileTimeeventsystemmEventmServe mTimeStepmSystemrSystem rBuildEventsrmSystem evalSystemunitmaxQueue allWaiting countWaitingwaitinginSystemtotalserveridleidleAvgPCategory ThreeOrLess FourToTen MoreThanTencustServnextCustbarbers customersruns barberEvent barberEvents barberSystemcatperc barberIdle customerWait $fEqCategory $fOrdCategory$fShowCategoryCardRankPlainJackQueenKingAceSuitClubSpadeHeartDiamondMarbleRG Collection selectOneselect1select2bucketjarpRGBpRGplainsfacesisFaceisPlainrankssuitsdeckvalue totalValuedrawdrawFdrawTo16win chanceWin $fEqMarble $fOrdMarble $fShowMarble$fEqSuit $fOrdSuit $fShowSuit $fEnumSuit$fEqRank $fOrdRank $fShowRank StrategyMOutcomeWinLoseStrategyDoorsprizechosenopenedDoorAdoorsstarthideopenswitchstaygameresultevalsimEval firstChoiceswitch'stayMswitchMevalM$fEqDoor $fOrdDoor $fShowDoor $fEqOutcome $fOrdOutcome $fShowOutcomeScore gameRoundgameFastgameFastEither gameFastFixgameLeastScoreflattenedMatrix startVector compareMaybecumulaterunExacttracechopmeeting bruteforce runSimulationlatexDielatexMarkedDielatexFromChainlatexChoppedFromChain makeChainsrollcontinuestrategyNodesESPredSTransPStatehappensnetworksourcebingaEbE $fEqNodes $fOrdNodes $fShowNodesVisPlotysxscolor lineStyle lineWidthlabelPlotFun LineStyleSolidDashedDottedDotDashLongDashTwoDashColorBlackBlueGreenRedBrownGrayPurpleDarkGrayCyan LightGreenMagentaOrangeYellowWhiteCustom FigureEnvFEfileNametitlexLabelyLabelfigureplotcolorssetColor autoColorplotDplotRDplotFplotLplotRLyls metaTupleincrdecrfigfigP showParamslegenddrawyvecout0out1 $fShowColor$fShowLineStyle$fShowFigureEnv $fEqColor $fEqLineStyleTreeAliveHitFallenHeightgrowhitfallevolveseedtreehistsimTreesimHistt2h2st2sh2heightp1p2p3p4 heightAtTimep5 heightCurvep6doneev5 $fOrdTree$fEqTree $fShowTreedsv0p0dvdpdvpvpvspsfig1EitherTthrowiteratedoWhilewhile whileTraceLinesasLinesshowNQindent printListasTupleasSeqasListasSetasLispasPlainasPlain'asStringasCasesasDefs asParagraphsshowRghc-prim GHC.ClassesOrdbaseGHC.BaseMonadEqfmapjoinGHC.NumNum GHC.TypesIO