gpt4 book ai didi

rust - 这个 for 循环模式有没有名字,如果有,有没有更好的写法?

转载 作者:行者123 更新时间:2023-12-03 11:24:44 25 4
gpt4 key购买 nike

这是我所指模式的示例函数:

fn check_sub_listiness<T: PartialEq>(big_list: &[T], small_list: &[T]) -> bool {
for poss_sublist in big_list.windows(small_list.len()) {
if poss_sublist == small_list {
return true;
}
}
false
}
此代码接受一个大列表和一个小列表,并返回小列表是否是大列表的子列表。我把它写成我正在做的锻炼练习的一部分。
我发现自己经常使用这种模式,在那里我遍历一些选项,检查条件,如果找到则返回 true,如果我在循环结束时没有找到我要找的内容,则返回 false。有这个名字吗?更重要的是,是否有更好的语义方式来编写它(用 Rust 或任何其他语言)。

最佳答案

迭代直到成功就像 .find() 但如果您只对 true 感兴趣/false结果你可以使用 .any() ,这正是您所要求的。

Tests if any element of the iterator matches a predicate.

any() takes a closure that returns true or false. It applies this closure to each element of the iterator, and if any of them return true, then so does any(). If they all return false, it returns false.

any() is short-circuiting; in other words, it will stop processing as soon as it finds a true, given that no matter what else happens, the result will also be true.

An empty iterator returns false.


所以你的循环可以这样写:
fn check_sub_listiness<T: PartialEq>(big_list: &[T], small_list: &[T]) -> bool {
big_list.windows(small_list.len()).any(|poss_sublist| {
poss_sublist == small_list
})
}

关于rust - 这个 for 循环模式有没有名字,如果有,有没有更好的写法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65246679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com