Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Random.Bool.weightedBool #30

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions elm.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"version": "3.2.0",
"exposed-modules": [
"Random.Array",
"Random.Bool",
"Random.Char",
"Random.Date",
"Random.Dict",
Expand Down
41 changes: 41 additions & 0 deletions src/Random/Bool.elm
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
module Random.Bool exposing (weightedBool)

{-| Extra functions for generating Bools.


# Values

@docs weightedBool

-}

import Random exposing (Generator)


{-| Generates True with probability given by the argument (number 0..1, clamped
to these bounds if needed)

weightedBool -0.5 -- always generates False

weightedBool 0 -- always generates False

weightedBool 0.25 -- biased coin, generates True 25% of the time

weightedBool 0.5 -- fair coin, same as Random.Extra.bool

weightedBool 0.75 -- biased coin, generates True 75% of the time

weightedBool 1 -- always generates True

weightedBool 1.5 -- always generates True

-}
weightedBool : Float -> Generator Bool
weightedBool probability =
let
clampedProbability : Float
clampedProbability =
clamp 0 1 probability
in
Random.float 0 1
|> Random.map (\float -> float <= clampedProbability)