add indexed_apply_

This commit is contained in:
blueloveTH 2024-04-27 21:16:11 +08:00
parent 6cc4d9c5cc
commit 4f431f4095
3 changed files with 17 additions and 0 deletions

View File

@ -38,6 +38,7 @@ class array2d(Generic[T]):
def fill_(self, value: T) -> None: ... def fill_(self, value: T) -> None: ...
def apply_(self, f: Callable[[T], T]) -> None: ... def apply_(self, f: Callable[[T], T]) -> None: ...
def indexed_apply_(self, f: Callable[[int, int, T], T]) -> None: ...
def copy_(self, other: 'array2d[T] | list[T]') -> None: ... def copy_(self, other: 'array2d[T] | list[T]') -> None: ...
# algorithms # algorithms

View File

@ -229,6 +229,16 @@ struct Array2d{
return vm->None; return vm->None;
}); });
vm->bind(type, "indexed_apply_(self, f)", [](VM* vm, ArgsView args){
Array2d& self = PK_OBJ_GET(Array2d, args[0]);
PyObject* f = args[1];
for(int i = 0; i < self.numel; i++){
std::div_t res = std::div(i, self.n_cols);
self.data[i] = vm->call(f, VAR(res.rem), VAR(res.quot), self.data[i]);
}
return vm->None;
});
vm->bind(type, "copy_(self, other)", [](VM* vm, ArgsView args){ vm->bind(type, "copy_(self, other)", [](VM* vm, ArgsView args){
Array2d& self = PK_OBJ_GET(Array2d, args[0]); Array2d& self = PK_OBJ_GET(Array2d, args[0]);
if(is_type(args[1], VM::tp_list)){ if(is_type(args[1], VM::tp_list)){

View File

@ -166,3 +166,9 @@ try:
exit(1) exit(1)
except TypeError: except TypeError:
pass pass
a = array2d(3, 4)
a.indexed_apply_(lambda x, y, val: x+y)
assert a[0, 0] == 0
assert a[1, 2] == 3
assert a[2, 0] == 2