Condition

patt/;test

is a pattern which matches only if the evaluation of test yields True.

lhs:>rhs/;test

represents a rule which applies only if the evaluation of test yields True.

lhs:=rhs/;test

is a definition to be used only if test yields True.

Details

  • All pattern variables used in test must also appear in patt.
  • lhs:=Module[{vars},rhs/;test] allows local variables to be shared between test and rhs. You can use the same construction with Block and With. »

Examples

open allclose all

Basic Examples  (2)

Make a definition with the condition that x should be positive:

Replace all elements which satisfy the condition of being negative:

Scope  (2)

Share a variable between a condition and function body:

Use Condition inside a function body to control evaluation:

Properties & Relations  (2)

Condition evaluates a Boolean expression on named parts of a pattern:

PatternTest applies test functions to patterns, which need not have names:

Use Except to effectively negate Condition:

Possible Issues  (1)

Repeated[p /; test] requires that every named pattern in p have the same value throughout the sequence:

The same is true of RepeatedNull:

Use PatternTest in combination with unnamed patterns to allow a sequence of nonidentical elements:

Wolfram Research (1988), Condition, Wolfram Language function, https://reference.wolfram.com/language/ref/Condition.html.

Text

Wolfram Research (1988), Condition, Wolfram Language function, https://reference.wolfram.com/language/ref/Condition.html.

CMS

Wolfram Language. 1988. "Condition." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/Condition.html.

APA

Wolfram Language. (1988). Condition. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Condition.html

BibTeX

@misc{reference.wolfram_2023_condition, author="Wolfram Research", title="{Condition}", year="1988", howpublished="\url{https://reference.wolfram.com/language/ref/Condition.html}", note=[Accessed: 18-March-2024 ]}

BibLaTeX

@online{reference.wolfram_2023_condition, organization={Wolfram Research}, title={Condition}, year={1988}, url={https://reference.wolfram.com/language/ref/Condition.html}, note=[Accessed: 18-March-2024 ]}