# HG changeset patch # User IBBoard # Date 1563108253 -3600 # Node ID 98be775c533c96bce1824d365e75f9daec785d2d # Parent d3e35dfc6f84b0cbf8a52d94cf3283f01f8302d5 An odd "non-determinism" example from StackOverflow It is clever, but doesn't make much sense as to how it gets its results diff -r d3e35dfc6f84 -r 98be775c533c 7-Haskell/cointoss.hs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/7-Haskell/cointoss.hs Sun Jul 14 13:44:13 2019 +0100 @@ -0,0 +1,30 @@ +module CoinToss where + -- Based on https://stackoverflow.com/questions/20638893/how-can-non-determinism-be-modeled-with-a-list-monad + -- Because it only throws "*** Exception: :57:1-26: Non-exhaustive patterns in function toss" in gchi + import Control.Monad -- Required for guard, but not mentioned in the example + + data CoinType = Fair | Biased deriving (Show) + data Coin = Head | Tail deriving (Eq,Show) + + toss Fair = [Head, Tail] + toss Biased = [Head, Head] + + pick = [Fair, Biased] + + experiment = do + coin <- pick -- Pick a coin at random (Non-determinism takes both coins) + result <- toss coin -- Toss it, to get a result (Non-determinism joins all possible toss results in a single list) + guard (result == Head) -- We only care about results that come up Heads (Non-determinism does something weird and inexplicable) + return coin -- Return which coin was used in this case (Magic has happened here and we've suddenly gone from "Head, Tail, Head, Head" to "Fair, Biased, Biased") + + part_experiment = do + coin <- pick -- Pick a coin at random + result <- toss coin -- Toss it, to get a result + return result -- Return the intermediary results + + part_experiment_2 = do + coin <- pick -- Pick a coin at random + result <- toss coin -- Toss it, to get a result + return guard (result == Head) -- Return the intermediary results + + -- Load the module and then run "experiment" and you get [Fair,Biased,Biased], which apparently shows that there's a 2/3 chance it's a biased coin \ No newline at end of file