Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
830 views
in Technique[技术] by (71.8m points)

haskell - How can non-determinism be modeled with a List monad?

Can anyone explain (better with an example in plain English) what a list monad can do to model non-deterministic calculations? Namely what the problem is and what solution a list monad can offer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an example based on coin tossing. The problem is as follows:

You have two coins, labeled Biased and Fair. The Biased coin has two heads, and the Fair coin has one head and one tail. Pick one of these coins at random, toss it and observe the result. If the result is a head, what is the probability that you picked the Biased coin?

We can model this in Haskell as follows. First, you need the types of coin and their faces

data CoinType = Fair | Biased deriving (Show)

data Coin = Head | Tail deriving (Eq,Show)

We know that tossing a fair coin can come up either Head or Tail whereas the biased coin always comes up Head. We model this with a list of possible alternatives (where implicitly, each possibility is equally likely).

toss Fair   = [Head, Tail]
toss Biased = [Head, Head]

We also need a function that picks the fair or biased coin at random

pick = [Fair, Biased]

Then we put it all together like this

experiment = do
  coin   <- pick         -- Pick a coin at random
  result <- toss coin    -- Toss it, to get a result
  guard (result == Head) -- We only care about results that come up Heads
  return coin            -- Return which coin was used in this case

Notice that although the code reads like we're just running the experiment once, but the list monad is modelling nondeterminism, and actually following out all possible paths. Therefore the result is

>> experiment
[Biased, Biased, Fair]

Because all the possibilities are equally likely, we can conclude that there is a 2/3 chance that we have the biased coin, and only a 1/3 chance that we have the fair coin.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...