qubit_function/functions/function/box_conditional_function.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10// qubit-style: allow explicit-imports
11//! Defines the `BoxConditionalFunction` public type.
12
13use super::{
14 BoxFunction,
15 BoxPredicate,
16 Function,
17 Predicate,
18 impl_box_conditional_function,
19 impl_conditional_function_debug_display,
20};
21
22// ============================================================================
23// BoxConditionalFunction - Box-based Conditional Function
24// ============================================================================
25
26/// BoxConditionalFunction struct
27///
28/// A conditional function that only executes when a predicate is satisfied.
29/// Uses `BoxFunction` and `BoxPredicate` for single ownership semantics.
30///
31/// This type is typically created by calling `BoxFunction::when()` and is
32/// designed to work with the `or_else()` method to create if-then-else logic.
33///
34/// # Features
35///
36/// - **Single Ownership**: Not cloneable, consumes `self` on use
37/// - **Conditional Execution**: Only transforms when predicate returns `true`
38/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
39/// - **Implements Function**: Can be used anywhere a `Function` is expected
40///
41/// # Examples
42///
43/// ## With or_else Branch
44///
45/// ```rust
46/// use qubit_function::{Function, BoxFunction};
47///
48/// let double = BoxFunction::new(|x: &i32| x * 2);
49/// let negate = BoxFunction::new(|x: &i32| -x);
50/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
51///
52/// assert_eq!(conditional.apply(&5), 10); // when branch executed
53/// assert_eq!(conditional.apply(&-5), 5); // or_else branch executed
54/// ```
55///
56pub struct BoxConditionalFunction<T, R> {
57 pub(super) function: BoxFunction<T, R>,
58 pub(super) predicate: BoxPredicate<T>,
59}
60
61// Use macro to generate conditional function implementations
62impl_box_conditional_function!(
63 BoxConditionalFunction<T, R>,
64 BoxFunction,
65 Function
66);
67
68// Use macro to generate conditional function debug and display implementations
69impl_conditional_function_debug_display!(BoxConditionalFunction<T, R>);