user8370684
user8370684

Reputation:

Is there an equivalent to Haskell's iterate in Rust?

Haskell's iterate function repeatedly applies a function to a value to generate a series of values. For example, applying (^2) to 2 generates 2, 2^2, 2^2^2, 2^2^2^2, ... (2, 4, 16, 256, ...)

Is there an equivalent in Rust?

Upvotes: 4

Views: 406

Answers (3)

Dan N
Dan N

Reputation: 167

As of Rust 1.34, you can use std::iter::successors

So for this problem you would do something like this:

playpen

use std::iter::successors;

fn main() {
    let v = successors(Some(2_u128), |n| n.checked_mul(*n)).collect::<Vec<_>>();
    assert_eq!(v, vec![2, 4, 16, 256, 65536, 4294967296, 18446744073709551616]);

    for i in successors(Some(2_u128), |n| n.checked_mul(*n)) {
        println!("{}", i);
    }
}

Also look at std::iter::from_fn, it can be quite a bit more powerful.

Upvotes: 2

SirDarius
SirDarius

Reputation: 42969

This does not exist in the standard library, however the itertools crate has iterate

Creates a new iterator that infinitely applies function to value and yields results.

use itertools::iterate;

itertools::assert_equal(iterate(1, |&i| i * 3).take(5), vec![1, 3, 9, 27, 81]);

Upvotes: 6

Jmb
Jmb

Reputation: 23463

itertools::iterate seems to be what you want.

Upvotes: 0

Related Questions