contains
Stable function · Expressions
Tier: stable · Kind: function · Topic: Expressions
| Julia | TypeScript | Python | Rust | Go |
|---|---|---|---|---|
| not exported | contains | contains | contains | Contains |
Julia
Julia does not export this function.
TypeScript
function contains(expr: Expr, varName: string): boolean
Check if an expression contains a specific variable
Parameters
expr— Expression to searchvarName— Variable name to look for
Returns
True if the variable appears in the expression
Example (expressions)
// Expressions are plain JSON trees; build one directly ...
const built: Expr = { op: '*', args: ['k', { op: '-', args: ['T_wall', 'T_air'] }] }
// ... or parse the text form, which is the inverse of `toAscii`.
const parsed = parseExpression('k * (T_wall - T_air)')
assert.deepEqual(parsed, built)
assert.deepEqual([...freeVariables(parsed)].sort(), ['T_air', 'T_wall', 'k'])
assert.equal(contains(parsed, 'T_wall'), true)
// Substitution is single-pass and returns a new tree.
const bound = substitute(parsed, { T_wall: 300, k: 0.05 })
assert.equal(toAscii(bound), '0.05 * (300 - T_air)')
assert.deepEqual([...freeVariables(bound)], ['T_air'])
assert.equal(toAscii(simplify(substitute(parsed, { T_wall: 300, T_air: 300 }))), '0')
const eq = parseEquation('D(T_air) = k * (T_wall - T_air)')
assert.deepEqual(eq.rhs, built)
assert.throws(() => parseExpression('k * (T_wall'), ExpressionParseError)
Python
contains(expr: Expr, var_name: str) -> bool
Check if an expression contains a specific variable.
Parameters
expr(Expr) — Expression to search invar_name(str) — Variable name to look for
Returns
bool— True if variable is found, False otherwise
Rust
pub fn contains(expr: &Expr, var_name: &str) -> bool
Check if an expression contains a specific variable
Arguments
expr- The expression to searchvar_name- The variable name to look for
Returns
trueif the variable is found,falseotherwise
Example (evaluate)
let expr = parse_expression("k * A - x")?;
let bindings = HashMap::from([
("k".to_string(), 2.0),
("A".to_string(), 3.0),
("x".to_string(), 1.0),
]);
assert_eq!(evaluate(&expr, &bindings), Ok(5.0));
// A missing binding is reported by name, not guessed.
let partial = HashMap::from([("k".to_string(), 2.0)]);
let mut unbound = evaluate(&expr, &partial).unwrap_err();
unbound.sort();
assert_eq!(unbound, ["A", "x"]);
assert!(contains(&expr, "A") && !contains(&expr, "B"));
assert_eq!(to_ascii(&simplify(&parse_expression("x * 1 + 0")?)), "x");