The random package contains a type class Uniform
for uniformly distributed types.
This works for types like:
data Coin = Heads | Tails
But let's say I want to model a set of things with a non-uniform distribution, for example by adding the possibility of the coin landing on its side:
data Coin = Heads | Tails | Side
Now I could still implement Uniform
with a non-uniform distribution in its implementation but that would be lying to the implicit rules of Uniform
.
Do I have to just use a standalone function or is there some type class for the concept of an "actual" distribution?
This type class would be useful in the context of an RPG where you could have some types
data Rarity = Common | Rare
data DropType = Club | Sword
where the chances of getting a Rare
and it being a Sword
might be lower than the other values.
But the concept of drawing a value from the set of all values of that type is still the same for Rarity
and DropType
which is why this looks like a job for type classes to me.
One option is using random-fu, which offers a categorical distribution. A quick example:
import Data.Random
import Data.Random.Distribution.Categorical
import Data.Random.Sample
data Coin = Heads | Tails | Side deriving Show
-- set up distribution, weights don't have to sum to 1
coin :: Categorical Double Coin
coin = fromList [(0.5, Heads), (0.5, Tails), (0.001, Side)]
-- draw a single sample from the distribution
main = sample coin >>= print
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With