Skip to main content

match_value

Function match_value 

Source
pub fn match_value(
    cx: &mut Cx,
    value: Value,
    arms: &[MatchArm],
) -> Result<PatternMatch>
Expand description

Matches value against arms in order, returning the first that accepts.

The kernel defines the Shape match/binding contract; this runs each arm’s shape over the value and reports the first hit with its captured ShapeBindings.

§Errors

Returns an error if no arm accepts the value.

§Examples

use std::sync::Arc;
use sim_kernel::{Cx, DefaultFactory, NoopEvalPolicy, Symbol};
use sim_lib_pattern::{
    AlgebraicDataType, MatchArm, VariantDeclaration, match_value,
};

let mut cx = Cx::new(Arc::new(NoopEvalPolicy), Arc::new(DefaultFactory));
let maybe = AlgebraicDataType::new(
    Symbol::qualified("adt", "Maybe"),
    vec![
        VariantDeclaration::nullary(Symbol::qualified("maybe", "Nothing")),
        VariantDeclaration::nullary(Symbol::qualified("maybe", "Just")),
    ],
)
.unwrap();
let nothing = maybe.constructor(&Symbol::qualified("maybe", "Nothing")).unwrap();
let just = maybe.constructor(&Symbol::qualified("maybe", "Just")).unwrap();
let value = just.construct(&mut cx, vec![]).unwrap();

let matched = match_value(
    &mut cx,
    value,
    &[
        MatchArm::for_constructor(&nothing),
        MatchArm::for_constructor(&just),
    ],
)
.unwrap();
assert_eq!(matched.arm_index(), 1);
assert_eq!(matched.label(), &Symbol::qualified("maybe", "Just"));