BurntSushi / BurntSushi/quickcheck

Implement something like choose_weighted for `Gen`

Open
#312 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
2.8k
Forks
165
PR merge metrics
No merged PRs in 30d

Description

Can we include something like [frequency](https://hackage.haskell.org/package/QuickCheck-2.14.2/docs/Test-QuickCheck.html#v:frequency) from Haskell's QuickCheck? It will generalize [this pattern](https://github.com/BurntSushi/quickcheck/blob/master/src/arbitrary.rs#L632) and make it more convenient to use, for example:
```rust
g.choose_weighted(&[
(10, g.gen_range(0..0xB0) as u8 as char),
(2, ...),
(5, ...),
(1, ...),
(1, ...),
(1, ...),
])
```
The implementation can be something like this:
```rust
impl Gen {

pub fn choose_weighted<'a, T>(&mut self, slice: &'a [(u32, T)]) -> Option<&'a T> {
slice.choose_weighted(&mut self.rng, |item| item.0).ok().map(|item| &item.1)
}

}
```
I know that in this particular example can be problem with eager evaluation which is not problem in Haskell since it is lazy, however, we can solve it by adding another associated function which chooses from closures instead of values. In other words, do it exactly like it is done for `Result` with `and`/`and_then` and `or`/`or_else` functions.

What do you think?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.