1 unstable release
new 0.1.0 | Jan 10, 2025 |
---|
#380 in Build Utils
51 downloads per month
10KB
131 lines
KT List Comprehensions
Python-like list comprehensions for Rust
Usage
After adding this crate to your dependencies, you can use
list comprehensions using the kt_list_comprehensions::list_comprehension![]
procedural macro.
Features
- One or more nested
for-in
clauses - Support for multiple
if
clauses - Supports Rust expressions and patterns
Examples
Simple list comprehensions
use kt_list_comprehensions::list_comprehension;
let vec = vec![-1, 2, 2, 3, 4];
let result: Vec<i32> = list_comprehension![x * 2 for x in vec if x > 0].collect();
assert_eq!(result, [4, 4, 6, 8]);
Nested for-in
clauses
use kt_list_comprehensions::list_comprehension;
let vec_of_vectors = vec![vec![1, 2, 3], vec![4, 5, 6]];
let result: Vec<i32> = list_comprehension![
x
for vec in vec_of_vectors
for x in vec
].collect();
assert_eq!(result, [1, 2, 3, 4, 5, 6]);
Multiple if
clauses
use kt_list_comprehensions::list_comprehension;
let vec = vec!["1", "2", "not a number", "-3"];
let parse_i32 = |string: &str| string.parse::<i32>();
let result: Vec<i32> = list_comprehension![
parse_i32(number).unwrap()
for number in vec
if parse_i32(number).is_ok()
if parse_i32(number).unwrap() > 0
].collect();
assert_eq!(result, [1, 2]);
Licensing
Dual-licensed under both the Apache License, Version 2.0 and the MIT License.
Contributing
Unless explicitly stated otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, will be dual-licensed as above, without any additional terms or conditions.
Dependencies
~235–690KB
~16K SLoC