10장: concepts로 범주론적 인터페이스 짜기
전체 목차 · 이전: 9장: 락 순서와 교착 상태 · 다음: 11장: 범주론적 인터페이스로 병렬 파이프라인 합성하기
2~3부는 세션 타입과 선형 타입을 옮겼습니다. 4부는 세 번째 이론 — 범주론(category theory)의 Functor, Monad — 를 C++23의 concepts 로 옮깁니다.
먼저: std::optional과 std::expected가 뭔가
이 장은 std::optional과 std::expected를 계속 씁니다. 둘 다 "값이 있을 수도, 없을 수도 있는 상황"을 표현하는 타입인데, 없는 이유를 설명할 수 있느냐가 다릅니다.
std::optional<T>는T타입의 값을 담거나, 아무것도 안 담을 수 있는 상자입니다. "찾았다/못 찾았다"처럼 실패 이유를 굳이 설명할 필요가 없을 때 씁니다.has_value()로 값이 들었는지 확인하고,value()(또는*opt)로 꺼냅니다.std::expected<T, E>는std::optional의 확장판입니다 — 값이 없을 때 그냥 "없다"로 끝나지 않고, 왜 없는지(E타입의 에러값)까지 같이 담습니다.has_value()로 성공/실패를 확인하고, 성공했으면value()로 값을, 실패했으면error()로 에러를 꺼냅니다.
std::optional<int> maybe_find(const std::vector<int>& v, int target) {
for (int x : v) if (x == target) return x;
return std::nullopt; // 못 찾았다 -- 이유는 없다
}
std::expected<int, std::string> parse_positive(int x) {
if (x <= 0) return std::unexpected("must be positive"); // 실패 + 이유
return x;
}둘 다 "실패할 수도 있는 계산의 결과"를 표현한다는 점에서, 예외를 던지는 대신 반환값 하나로 성공/실패를 다 담아 돌려주는 관용구입니다 — 호출하는 쪽이 try/catch 없이 if (result.has_value())만으로 분기할 수 있습니다. 이 장이 다루는 건 정확히 이 두 타입에 공통으로 새로 생긴 메서드(.transform(), .and_then())이고, 그 메서드들이 범주론의 Functor/Monad와 어떻게 맞아떨어지는지입니다.
concept으로 "Functor"를 정의하기
범주론에서 Functor는 "구조를 보존하면서 안의 값에 함수를 적용하는 것"이라고 정의됩니다. C++로 옮기면 — "transform이라는, 안의 값에 함수를 적용해서 같은 모양의 새 컨테이너를 돌려주는 메서드가 있는 것"입니다.
template <typename M>
concept Functor = requires(M m) {
{ m.transform([](auto x) { return x; }) };
};concept은 "이 요구사항(requires 블록 안의 표현식이 실제로 컴파일되는가)을 만족하는 타입만 이 이름으로 부를 수 있다"는 컴파일 타임 술어입니다. Functor<M>은 "`M` 타입의 값에 .transform(함수)를 부를 수 있다"는 뜻입니다.
검증 1: std::optional과 std::expected가 실제로 Functor다
static_assert(Functor<std::optional<int>>);
static_assert(Functor<std::expected<int, std::string>>);
static_assert(!Functor<int>); // 평범한 int에는 .transform()이 없다 -- Functor가 아니다세 static_assert 모두 통과합니다 — 컴파일 시점에 확인됩니다. C++23의 std::optional과 std::expected는 둘 다 새로 .transform() 멤버 함수를 얻었습니다(이전 C++ 표준에는 없었습니다 — 아래 팁 박스에서 다시 다룹니다). 이제 이걸 8장에서 완성한 WorkerSession에 실제로 적용해봅시다 — 워커가 배치를 처리한 결과를 감쌀 타입부터 정의합니다.
struct BatchResult {
int worker_id;
long checksum; // 처리한 배치 내용의 간단한 체크섬
};
// WorkerSession이 붙든 세그먼트를 실제로 "처리"하는 연산.
// 세그먼트 ID가 음수면 손상된 배치로 보고 실패를 표현한다.
std::expected<BatchResult, std::string> process_batch(const WorkerSession& session, int worker_id, int segment_id) {
if (segment_id < 0) return std::unexpected("corrupt segment id");
return BatchResult{worker_id, static_cast<long>(segment_id) * 31};
}Idle conn;
WorkerSession session(std::move(conn).connect(), DataSegmentHandle(7));
auto result = process_batch(session, /*worker_id=*/1, /*segment_id=*/7);
auto doubled = result.transform([](BatchResult r) { r.checksum *= 2; return r; });
std::cout << "checksum: " << doubled->checksum << "\n";
WorkerSession bad_session(std::move(Idle{}).connect(), DataSegmentHandle(-99));
auto bad_result = process_batch(bad_session, 2, -99);
auto bad_doubled = bad_result.transform([](BatchResult r) { r.checksum *= 2; return r; });
std::cout << "error propagated: " << (bad_doubled.has_value() ? "has value" : bad_doubled.error()) << "\n";$ clang++ -std=c++23 -O0 functor_concept.cpp -o functor_concept && ./functor_concept
coordinator connected to worker
acquired segment 7
checksum: 434
coordinator connected to worker
acquired segment -99
error propagated: corrupt segment idbad_result(에러 상태)에 .transform()을 걸면, 함수는 아예 호출되지 않고 에러가 그대로 전파됩니다(bad_doubled.error()가 원래 "corrupt segment id"를 그대로 갖고 있습니다) — 범주론이 Functor를 "구조를 보존한다"고 정의하는 바로 그 성질입니다. 배치 처리가 성공했으면 값에 함수를 적용하고, 실패했으면 그 "실패"라는 구조 자체는 그대로 유지됩니다.
Functor 법칙을 실제로 확인하기
Functor는 아무 transform이나 다 되는 게 아니라 법칙을 지켜야 합니다 — 그중 항등 법칙(identity law): m.transform(항등함수)는 m 자신과 같아야 합니다.
std::expected<BatchResult, std::string> r = BatchResult{1, 217};
auto r2 = r.transform([](BatchResult v) { return v; });
std::cout << "functor identity law holds: "
<< (r->worker_id == r2->worker_id && r->checksum == r2->checksum) << "\n";functor identity law holds: 1r2가 정말로 r과 같은 값(worker_id, checksum 둘 다)이라는 걸 확인합니다 — concept Functor가 요구하는 건 ".transform()이 존재한다"는 문법적 조건뿐이지만, 그 뒤에 있는 의미론적 법칙(항등, 결합)까지는 concept이 검사해주지 않는다는 것도 짚어둘 만합니다. 이건 2장에서 이미 짚은 "인코딩이지 이식이 아니다"의 또 다른 사례입니다 — concept은 "이 함수가 있다"는 걸 컴파일 타임에 강제하지만, "이 함수가 Functor 법칙을 지킨다"는 건 여전히 프로그래머의 책임이자, 테스트로 확인해야 할 몫입니다.
Monad: and_then으로 실패를 자동으로 전파하기
Functor보다 한 단계 더 나가면 Monad입니다 — "효과를 값으로 만들고 합성하는" 도구입니다. std::expected::and_then이 정확히 이 역할을 합니다. 워커가 배치를 처리한 뒤, 그 결과를 검증하고, 검증된 결과를 5장의 ResultChannel로 보고까지 잇는 두 단계 파이프라인을 만들어봅시다.
std::expected<BatchResult, std::string> validate(BatchResult r) {
if (r.checksum == 0) return std::unexpected("checksum is zero -- suspicious batch");
return r;
}
std::expected<Reported, std::string> report(BatchResult r, ResultChannel ch) {
return std::move(ch).send(static_cast<int>(r.checksum));
}
Idle conn;
WorkerSession session(std::move(conn).connect(), DataSegmentHandle(7));
auto pipeline = process_batch(session, 1, 7)
.and_then(validate)
.and_then([](BatchResult r) { return report(r, ResultChannel{}); });
std::cout << "pipeline succeeded: " << pipeline.has_value() << "\n";
WorkerSession bad_session(std::move(Idle{}).connect(), DataSegmentHandle(-99));
auto bad_pipeline = process_batch(bad_session, 2, -99)
.and_then(validate)
.and_then([](BatchResult r) {
std::cout << "this must not print\n";
return report(r, ResultChannel{});
});
std::cout << "bad pipeline succeeded: " << bad_pipeline.has_value() << " (" << bad_pipeline.error() << ")\n";pipeline succeeded: 1
bad pipeline succeeded: 0 (corrupt segment id)정상 경로는 process_batch → validate → report까지 이어져 성공합니다. 실패 경로는 process_batch에서 이미 "corrupt segment id"로 실패하고, 그다음 and_then들의 람다는 아예 실행되지 않습니다("this must not print"가 실제로 출력되지 않았습니다) — 이게 Monad의 핵심 힘입니다. 각 단계가 std::expected<T, std::string>를 돌려주므로 .transform()을 썼다면 중첩된 expected가 됐을 텐데, and_then은 그 중첩을 자동으로 "평평하게(flatten)" 만들어서 매번 if (!result) return result;를 손으로 안 써도 실패가 자동으로 전파되게 합니다.
팁 박스: C++17 환경이라면
Note |
(람다는 C++17에서 "평가되지 않는 문맥"( 우리가 직접 |
요약
concept Functor로 ".transform()이 있는 타입"을 정의하고, C++23의std::optional/std::expected가 실제로 그 요구사항을 만족한다는 걸static_assert로 컴파일 타임에 확인했습니다.8장에서 완성한
WorkerSession이 배치를 처리한 결과(BatchResult)를std::expected<BatchResult, std::string>으로 감싸,.transform()이 에러 상태에서는 함수를 호출하지 않고 그 상태를 그대로 보존한다는 것(Functor의 구조 보존)과, 항등 법칙이 실제로 성립한다는 것도 코드로 검증했습니다 — 다만concept은 문법만 강제하지 의미론적 법칙까지는 강제하지 않는다는 것도 짚었습니다..and_then()(Monad의 bind)으로process_batch→validate→ (5장의)ResultChannel로의report까지 잇는 파이프라인을 짜서, 중간 단계가 실패하면 그다음 단계가 정말로 스킵된다는 걸 실행 결과로 확인했습니다.C++17에는
.transform()/.and_then()자체가 없어서,concept대신void_tSFINAE 트레잇으로 검사 메커니즘은 흉내 낼 수 있지만std::optional은 그 시절엔 진짜로 Functor가 아니었다는 것까지 실제 코드로 확인했습니다.
다음 장에서는 이 Functor/Monad 인터페이스로 병렬 파이프라인을 합성합니다 — 여러 WorkerSession을 std::async로 동시에 돌리고, 이 장의 and_then으로 그 결과들을 안전하게 합성해서, 실패가 안전하게 전파되는 병렬 작업 체인을 짭니다.