Navigation
Synopsis Let the current alternative of a pattern match fail.
Syntax fail;
Description A fail statement is only allowed in statements that are controlled by the outcome of a pattern match:
  • The Patterns in a PatternWithAction in Switch or Visit statement controls the statements in the action part.
  • The test (expression) of a While or Do statement controls the statements in the body part.
  • The test (expressions) of a For statement control the statements in the body part.
  • The formal parameter declaration of a Function.
The fail statement is associated with the innermost pattern match by which it is controlled.

When fail is executed:
  • If the associated pattern has more alternatives, the next alternative is explored,
  • otherwise the pattern as a whole fails.
    • In the case of switch or visit this means that the next case will be tried. Any bindings caused by the pattern or side-effects caused by the action are undone.
    • For while, do and for, this implies that any bindings caused by the pattern are undone and that the next alternative in the test is tried; otherwise the loop is terminated.
    • For a function call it means that the next function declaration (or the default one) is tried.
Examples Here is an example taken from Recipes:Bubble. It uses a fail for the case that no unsorted element can be found in the list of numbers. As a result, the whole case fails and the default case is used.
rascal>import IO;
ok
rascal>public list[int] sort(list[int] Numbers){
>>>>>>>  switch(Numbers){
>>>>>>>    case [list[int] Nums1, int P, int Q, list[int] Nums2]:
>>>>>>>       if(P > Q){
>>>>>>>          return sort(Nums1 + [Q, P] + Nums2);
>>>>>>>       } else {
>>>>>>>       	  fail;
>>>>>>>       }
>>>>>>>     default: return Numbers;
>>>>>>>   }
>>>>>>>}
list[int] (list[int]): list[int] sort(list[int]);
rascal>sort([10, 1, 5, 3]);
list[int]: [10,1,5,3]
Is this page unclear, or have you spotted an error? Please add a comment below and help us to improve it. For all other questions and remarks, visit ask.rascal-mpl.org.