Skip to main content

pattern_core/graph/transform/
context.rs

1//! map_with_context: snapshot-based context-aware element mapping.
2//!
3//! Ported from `Pattern.Graph.Transform.mapWithContext` in the Haskell reference.
4
5use crate::graph::graph_classifier::{GraphClassifier, GraphValue};
6use crate::graph::graph_query::GraphQuery;
7use crate::graph::graph_view::GraphView;
8use crate::pattern::Pattern;
9
10// ============================================================================
11// map_with_context
12// ============================================================================
13
14/// Map elements in the view using the view's query as context.
15///
16/// The mapping function `f` receives a reference to the view's `GraphQuery`
17/// (a snapshot taken before any transformation) and the element pattern by value.
18/// All elements see the same snapshot — the query is not updated as elements
19/// are transformed.
20///
21/// The view is consumed; the returned view has the same query (cloned from the
22/// snapshot) and transformed elements.
23#[inline]
24pub fn map_with_context<Extra, V: GraphValue>(
25    _classifier: &GraphClassifier<Extra, V>,
26    f: impl Fn(&GraphQuery<V>, Pattern<V>) -> Pattern<V>,
27    view: GraphView<Extra, V>,
28) -> GraphView<Extra, V> {
29    // Take a snapshot of the query before any transformation.
30    let snapshot = view.view_query.clone();
31
32    let view_elements = view
33        .view_elements
34        .into_iter()
35        .map(|(cls, p)| (cls, f(&snapshot, p)))
36        .collect();
37
38    GraphView {
39        view_query: snapshot,
40        view_elements,
41    }
42}