简体   繁体   English

Haskell 数据类型的非均匀分布

[英]Non-uniform Distributions for Haskell data types

The random package contains a type class Uniform for uniformly distributed types.随机package 包含类型 class Uniform用于均匀分布的类型。 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:但是假设我想要 model 一组具有非均匀分布的事物,例如通过添加硬币落在其一侧的可能性:

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 .现在我仍然可以在其实现中使用非均匀分布来实现Uniform ,但这将与Uniform的隐含规则相悖。

Do I have to just use a standalone function or is there some type class for the concept of an "actual" distribution?我是否必须只使用独立的 function 或者是否有某种类型的 class 用于“实际”分布的概念?

This type class would be useful in the context of an RPG where you could have some types这种类型 class 在你可以有一些类型的 RPG 上下文中很有用

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.获得RareSword的机会可能低于其他值。 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.但是从该类型的所有值的集合中提取一个值的概念对于RarityDropType来说仍然是相同的,这就是为什么这对我来说看起来像是类型类的工作。

One option is using random-fu , which offers a categorical distribution .一种选择是使用提供分类分布的random-fu 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM