forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctools.rs
More file actions
43 lines (37 loc) · 1.28 KB
/
functools.rs
File metadata and controls
43 lines (37 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
pub(crate) use _functools::make_module;
#[pymodule]
mod _functools {
use crate::function::OptionalArg;
use crate::iterator;
use crate::pyobject::{PyObjectRef, PyResult, TypeProtocol};
use crate::vm::VirtualMachine;
#[pyfunction]
fn reduce(
function: PyObjectRef,
sequence: PyObjectRef,
start_value: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
let iterator = iterator::get_iter(vm, sequence)?;
let start_value = if let OptionalArg::Present(val) = start_value {
val
} else {
iterator::call_next(vm, &iterator).map_err(|err| {
if err.isinstance(&vm.ctx.exceptions.stop_iteration) {
let exc_type = vm.ctx.exceptions.type_error.clone();
vm.new_exception_msg(
exc_type,
"reduce() of empty sequence with no initial value".to_owned(),
)
} else {
err
}
})?
};
let mut accumulator = start_value;
while let Ok(next_obj) = iterator::call_next(vm, &iterator) {
accumulator = vm.invoke(&function, vec![accumulator, next_obj])?
}
Ok(accumulator)
}
}