%mathpiper,def="DefinePattern",private="true"

Rulebase("DefinePattern",{leftOperand, rightOperand, rulePrecedence, postPredicate});



Rule("DefinePattern",4,9,IsEqual(Type(leftOperand),"_"))
[
    DefinePattern(leftOperand[1], rightOperand, rulePrecedence, leftOperand[2]);
];



Rule("DefinePattern",4,10,True)
[
      Local(patternFlat,patternVariables, pattern, patternOperator, arg, arity);
      
      Bind(patternFlat, FunctionToList(leftOperand)); //Turn the pattern into a list.
      
      Bind(patternVariables, Rest(patternFlat)); //Remove the function name from the list.
      
      Bind(patternOperator,ToString(First(patternFlat))); //Obtain the function name.
      
      Bind(arity,Length(patternVariables)); //Obtain the arity of the function.
      
      DefLoadFunction(patternOperator);  //Load the function if it exists.
    
      /*
            If the function does not exist, create it.
      */
      If(Not(RulebaseDefined(patternOperator,arity)),
         [
          MacroRulebase(patternOperator,MakeVector(arg,arity));
         ]
        );
    
      Bind(pattern,PatternCreate(patternVariables,postPredicate));
    
      MacroRulePattern(patternOperator,arity,rulePrecedence, pattern)rightOperand;
    
      True;
];

%/mathpiper



DefinePattern(leftOperand[2],rightOperand,leftOperand[1],True);


%mathpiper_docs,name="DefinePattern",categories="Programmer Functions;Programming;Built In"
*CMD DefinePattern --- defines a rule which uses a pattern as its predicate

*CALL
	DefinePattern("operator", arity, precedence, pattern) body
*PARMS

{"operator"} -- string, name of function

{arity}, {precedence} -- integers

{pattern} -- a pattern object

{body} -- expression, body of rule

*DESC
This function defines a rule which uses a pattern as its predicate.

*SEE MacroRulePattern
%/mathpiper_docs
