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

Single item version of sample_iter ? #432

Closed
dtrebilco opened this issue May 7, 2018 · 2 comments
Closed

Single item version of sample_iter ? #432

dtrebilco opened this issue May 7, 2018 · 2 comments
Labels
T-sequences Topic: sequences

Comments

@dtrebilco
Copy link

Would it be worth adding a single item version of seq sample_iter()? My use cases typically only need one item. Code like this:

pub fn sample_one_iter<T, I, R>(rng: &mut R, iterable: I) -> Option<T>
    where I: IntoIterator<Item=T>,
          R: Rng + ?Sized,
{
    let mut count : usize = 0;
    let mut ret_val = None;
    for i in iterable {
        count += 1;
        if Uniform::sample_single(0, count, rng) == 0 {
            ret_val = Some(i);
        }
    }
    ret_val
}

As the current version does allocate memory which is a waste in the single case. For completeness you could also add the slice versions, but it does border on trivial.

pub fn sample_one_slice<R, T>(rng: &mut R, slice: &[T]) -> T
    where R: Rng + ?Sized,
          T: Clone
{
    slice[Uniform::sample_single(0, slice.len(), rng)].clone()
}

pub fn sample_one_slice_ref<'a, R, T>(rng: &mut R, slice: &'a [T]) -> &'a T
    where R: Rng + ?Sized
{

    &slice[Uniform::sample_single(0, slice.len(), rng)]
}

I can do a PR if needed.

@dhardy
Copy link
Member

dhardy commented May 7, 2018

See dhardy#82

This is still postponed, pending the 0.5 release.

@dhardy dhardy added the T-sequences Topic: sequences label May 7, 2018
@dhardy
Copy link
Member

dhardy commented May 28, 2018

I think #483 covers this? I'd welcome more feedback on that API design.

@dhardy dhardy closed this as completed May 28, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
T-sequences Topic: sequences
Projects
None yet
Development

No branches or pull requests

2 participants