#comprehension #python #iterator #list #generator

无std iter-python

Python生成器表达式和“列表”理解

6个版本

0.10.1 2021年12月12日
0.10.0 2021年12月12日
0.9.2 2019年3月20日
0.9.1 2019年3月17日
0.9.0 2019年3月10日

#1909 in Rust patterns

MIT 许可证

19KB
301

iter-python

Python生成器表达式 (i!) 和 "列表" 理解 (v!)

Repository Latest version Documentation MSRV unsafe forbidden License

用法

  1. 将以下行添加到您的 Cargo.toml,在 [dependencies]

    iter-python = "0.10.0"
    
  2. 使用以下代码在您的Rust代码中将 i! 和 (增强的) v!ec 带入作用域:

    use ::iter_python::prelude::*;
    

示例

use ::iter_python::prelude::{*,
    // Not necessary, but since `v` supersedes stdlib's `vec`'s API,
    // you can do this if you feel like it.
    v as vec,
};

fn main ()
{
    // `i!` macro for comprehension "lists" (iterators):
    let infinite_odds = || i!(2 * n + 1 for n in 0..);
    let sums_of_odds = i!(infinite_odds().take(n).sum() for n in 1..);
    assert!(sums_of_odds.take(100).all(is_square));
 /* The above may be suprising, but is an obvious mathematical property
    once we represent it as:

    1> 1   3   5   M-1
           |   |    |
    3> 1---2   4   M-#
               |    |
    5> 1---2---3   M-n
                    |
    M> 1---#---n---n+1  where M=2n+1
 */

    // `v!` macro: like `vec!`, but supporting `i!`'s input as well.
    let v = v![
        2 * x
        for &x_opt in &[None, Some(21), None]
        if let Some(x) = x_opt
    ];
    assert_eq!(
        dbg!(v),
        vec![42],  // `v!` does indeed feature classic `vec!` semantics.
    );


    // A more advanced example: generate the following string…
    const MATRIX: &str = "\
+-----+-----+-----+-----+-----+
| a11 | a12 | a13 | a14 | a15 |
| a21 | a22 | a23 | a24 | a25 |
| a31 | a32 | a33 | a34 | a35 |
| a41 | a42 | a43 | a44 | a45 |
| a51 | a52 | a53 | a54 | a55 |
+-----+-----+-----+-----+-----+";
    const N: usize = 6;

    // … using only one allocation!
    // This is achieved by combining lazy iterators (`i!`) with
    // "lazy strings" / lazy `Display`ables: `lazy_format!`.
    use ::iter_python::macros::lazy_format; // prelude provides it as `f!`
    let line = || lazy_format!(
        "+-{}-+",
        "-+-".join(i!("---" for _ in 1..N))
    );
    let top_line = line();
    let body = "\n".join(i!(
        lazy_format!(
            "| {} |",
            " | ".join(i!(f!("a{i}{j}") for j in 1..N)),
        )
        for i in 1..N
    ));
    let bottom_line = line();
    // Heap-allocation and iterator consumption occurs here:
    let matrix = format!("{top_line}\n{body}\n{bottom_line}");
    assert_eq!(matrix, MATRIX);
}

fn is_square (n: u32)
  -> bool
{
    n == ((n as f64).sqrt().trunc() as u32).pow(2)
}

有关更多示例,请参阅 iter!vec!

no_std 支持

该crates支持 #![no_std],通过禁用默认的 "std" 功能。

依赖

~10KB