@reduce — 벡터를 스칼라로 줄이기
@reduce — 벡터를 스칼라로 줄이기
@reduce는 벡터의 모든 요소를 지정한 연산자로 순차적으로 가로 축소(수평 reduction)해서, 요소 개수와 무관하게 스칼라 값 하나로 만들어 주는 내장 함수예요. 반환 타입은 E인데요, 값의 타입(anytype)에 딱 맞는 타입으로 정해져서 나와요.
본문
@reduce(comptime op: std.lang.ReduceOp, value: anytype) E
value로 받은 벡터의 요소들을 지정된 연산자 op로 순차적으로 가로 축소해서, E 타입의 스칼라 값으로 변환해 줘요.
다만 모든 연산자가 모든 벡터 요소 타입에서 쓸 수 있는 건 아니에요:
- 모든 연산자는 정수 벡터에서 쓸 수 있어요.
.And,.Or,.Xor는bool벡터에서도 추가로 쓸 수 있어요..Min,.Max,.Add,.Mul은 부동소수점 벡터에서도 추가로 쓸 수 있어요.
한 가지 주의할 점이 있어요. 정수 타입에서의 .Add와 .Mul 축소는 래핑(wrapping) 처리돼요. 부동소수점 타입에서는 연산의 결합 법칙(associativity)이 보존되는데, 예외로 플로트 모드가 .optimized로 설정돼 있으면 그 보장이 사라져요.
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "vector @reduce" {
const V = @Vector(4, i32);
const value = V{ 1, -1, 1, -1 };
const result = value > @as(V, @splat(0));
// result is { true, false, true, false };
try comptime expectEqual(@Vector(4, bool), @TypeOf(result));
const is_all_true = @reduce(.And, result);
try comptime expectEqual(bool, @TypeOf(is_all_true));
try expectEqual(false, is_all_true);
}
$ zig test test_reduce_builtin.zig
1/1 test_reduce_builtin.test.vector @reduce...OK
All 1 tests passed.