我想获取生成器函数的返回类型。
例如
function* test(){
yield 'a';
yield 123;
return true;
}
// what I'm trying to get
type A = GetGeneratorReturn<test>; // -> A has type boolean
Run Code Online (Sandbox Code Playgroud)
我目前处于什么状态。
type B = ReturnType<ReturnType<typeof test>['next']>['value'];
// B has type `true | "a" | 123`
Run Code Online (Sandbox Code Playgroud)
(我想如果我得到 Union 类型 B 的第一项,我就可以获得返回类型)
这个问题可能看起来非常基本,但我很难弄清楚如何做到这一点。我有一个整数,我需要使用 for 循环来循环整数次。
首先,我尝试过 -
fn main() {
let number = 10; // Any value is ok
for num in number {
println!("success");
}
}
Run Code Online (Sandbox Code Playgroud)
这会打印错误
error[E0277]: `{integer}` is not an iterator
--> src/main.rs:3:16
|
3 | for num in number{
| ^^^^^^ `{integer}` is not an iterator
|
= help: the trait `std::iter::Iterator` is not implemented for `{integer}`
= note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the …Run Code Online (Sandbox Code Playgroud) 我的用例是我想扫描迭代器,并在原始迭代器的段上生成累积值(这是用于标记器)。换句话说,输入值和输出值之间不是一对一的映射。请注意,这filter_map()不起作用,因为我确实需要累加器值。
我发现.scan(),这几乎就是我想要的:
#![allow(unused)]
fn main() {
let a = [1, 2, 3];
let mut iter = a.iter().scan(1, |state, &x| {
if x == 2 {
return None;
}
// each iteration, we'll multiply the state by the element
*state = *state * x;
// then, we'll yield the negation of the state
Some(-*state)
});
println!("{:?}", &iter.next());
println!("{:?}", &iter.next());
println!("{:?}", &iter.next());
}
Run Code Online (Sandbox Code Playgroud)
除了上面的输出
Some(-1)
None
Some(-3)
Run Code Online (Sandbox Code Playgroud)
当我想要它输出时
Some(-1)
Some(-3)
None
Run Code Online (Sandbox Code Playgroud)
而且,不管你怎么想,这都行不通:
Some(-1)
None
Some(-3)
Run Code Online (Sandbox Code Playgroud)
因为我实际上并没有迭代 …
我正在读一本关于 Python 的书,其中说明了如何实现迭代器协议。
class Fibbs:
def __init__(self):
self.a = 0
self.b = 1
def __next__(self):
self.a, self.b = self.b, self.a + self.b
return self.a
def __iter__(self):
return self
Run Code Online (Sandbox Code Playgroud)
在这里,self它本身就是可迭代和迭代器,我相信?然而,下面的段落说:
请注意,迭代器实现了该
__iter__方法,实际上该方法将返回迭代器本身。在许多情况下,您可以将该__iter__方法放入另一个对象中,并在 for 循环中使用该对象。然后将返回你的迭代器。建议迭代器__iter__另外实现自己的方法(返回 self,就像我在这里所做的那样),这样它们本身就可以直接在 for 循环中使用。
这是否意味着您可以将__iter__()和放入__next__()两个不同的对象中?可以对属于不同类的对象执行此操作吗?只能对属于不同类的对象执行此操作吗?这可能是实现迭代器协议的有点奇怪的方式。但我只是想看看如何实现,前提是它实际上可以这样实现。
在 C 中,我可以使用索引以嵌套方式可变地迭代数组。在 Rust 中,我几乎可以使用索引做同样的事情,但是如果我想使用迭代器而不是索引怎么办?
例如,以下代码段可以成功编译,因为两个借用都是不可变的:
let xs = [0, 1, 2];
for x in &xs {
for y in &xs {
println!("x={} y={}", *x, *y);
}
}
Run Code Online (Sandbox Code Playgroud)
但是如果我想使用可变迭代器怎么办?
let mut xs = [0, 1, 2];
for x in &mut xs {
*x += 1;
for y in &mut xs {
*y += 1;
println!("x={} y={}", *x, *y);
}
}
Run Code Online (Sandbox Code Playgroud)
这导致:
error[E0499]: cannot borrow `xs` as mutable more than once at a time
Run Code Online (Sandbox Code Playgroud)
我理解需要引导对数据的写入访问,但我也想知道经验丰富的 Rust 用户如何仅使用迭代器来实现这一目标——假设索引仅用于教育目的。
我想要一个可以接受固定值类型的任何范围/视图的函数。
int main()
{
std::array<std::pair<int, int>, 2> a{...};
std::array<std::pair<int, int>, 3> b{...};
generic_fun(a);
generic_fun(b);
};
Run Code Online (Sandbox Code Playgroud)
我当然可以
template <std::ranges::range R>
requires std::same_as<std::ranges::range_value_t<R>,std::pair<int,int>>
auto generic_fun(R range)
{
for(const auto& element : range)
return element.first;
}
Run Code Online (Sandbox Code Playgroud)
但 Visual Studio IDE 不知道element.
我期望范围库有类似的类型
template <typename T>
struct view
{
template <std::ranges::range R>
requires std::same_as<std::ranges::range_value_t<R>, T>
view(R);
T* begin() const;
T* end() const;
};
Run Code Online (Sandbox Code Playgroud)
这会给我 ide 支持
auto generic_fun(view<std::pair<int,int>> a)
{
for (const auto& b : a)
return b.first;
}
Run Code Online (Sandbox Code Playgroud)
为什么范围库中不存在这样的类型?定义一个抽象出除范围/迭代器的值类型之外的所有类型的类型在技术上是不可行的吗?或者没有人关心这样做,因为唯一的原因是 ide 支持? …
for...of当我中断循环时,是否可以循环迭代器的一部分而不关闭迭代器?
例子:
function* numbers(i=0){
while(true) yield i++;
}
let nums=numbers();
// this loop prints numbers from 0 to 3
for(const n of nums){
if(n>3) break;
console.log(n);
}
// this loop doesn't print anything because `nums` has already been closed
for(const n of nums){
if(n>10) break;
console.log(n);
}Run Code Online (Sandbox Code Playgroud)
我知道我可以通过自己的调用来遍历迭代器iterator.next()。但我想知道是否可以用for...of语法来做到这一点。
我注意到有两种方法可以获得向量(或其他容器类)的结束迭代器:
std::end(myVector)
Run Code Online (Sandbox Code Playgroud)
和
myVector.end()
Run Code Online (Sandbox Code Playgroud)
这同样适用于其他各种容器迭代器功能begin,cend,cbegin,rend,rbegin,crend,crbegin,find,等,如果有这些之间的任何功能上的区别是什么我不知道是什么?如果没有,是否有一些历史原因让他们两个?
(如果这是重复的道歉,我已经搜索了全部,并且发现了这些方法中的一个或另一个的大量来源,但没有提到两者或比较两者.)
我正在编写一个方法,它接受在这里定义a Map的形式的输入.Map<Term, List<Integer>>Term
方法:
Map并使用Term属性过滤它们.min(List.size(), 5))并将输出添加到全局变量(例如totalSum)totalSum这是我到目前为止所写的:
inputMap
.entrySet()
.stream()
.filter(entry -> entry.getKey().field().equals(fieldName)) // Keep only terms with fieldName
.forEach(entry -> entry.getValue()
.map(size -> Math.min(entry.getValue().size(), 5))) // These 2 lines do not work
.sum();
Run Code Online (Sandbox Code Playgroud)
我无法将列表流作为输入,为每个列表输出一个整数并返回所有输出的总和.
我显然可以使用for循环来编写它,但我正在尝试学习Java 8,并且好奇如果使用它可以解决这个问题.
我有以下继承:
class Processor(object):
def get_listings(self):
"""
returns a list of data
"""
raise NotImplemented()
def run(self):
for listing in get_listings():
do_stuff(listing)
class DBProcessor(Processor):
def get_listings(self):
"""
return a large set of paginated data
"""
...
for page in pages:
for data in db.fetch_from_query(...):
yield data
Run Code Online (Sandbox Code Playgroud)
虽然这有效,但是这会失败len(self.get_listings())或任何其他列表操作.
我的问题是如何重构我的代码DBProcessor.get_listings可以处理列表操作,但是当它的迭代器调用它将返回一个生成器?
iterator ×10
rust ×3
c++ ×2
python ×2
c++-concepts ×1
c++20 ×1
collectors ×1
containers ×1
for-loop ×1
for-of-loop ×1
generator ×1
integer ×1
java ×1
java-8 ×1
java-stream ×1
javascript ×1
loops ×1
nested ×1
oop ×1
std-ranges ×1
stl ×1
typescript ×1