Conditional structures: Difference between revisions

Line 3,033:
ENDSELECT
</lang>
 
=={{header|TXR}}==
 
In TXR, most directives are conditionals, because they specify some kind of match. Given some directive D, the underlying logic in the language is, roughtly, "if D does not match at the current position in the input, then fail, otherwise the input advances according to the semantics of D".
 
An easy analogy to regular expressions may be drawn. The regex /abc/ means something like "if a doesn't match, then fail, otherwise consume a character and if b doesn't match, then fail, otherwise consume another character and if c doesn't match, then fail otherwise consume another character and succeed." The expressive power comes from, in part, not having to write all these decisions and book-keeping.
 
The interesting conditional-like structures in TXR are the parallel directives, which apply separate clauses to the same input, and then integrate the results in various ways.
 
For instance the <code>choose</code> construct will select, from among those clauses which match successfully, the one which maximizes or minimizes the length of an extracted variable binding:
 
<lang txr>
@(choose :shortest x)
@x:@y
@(or)
@x<--@y
@(or)
@x+@y
@(end)</lang>
 
Suppose the input is something which can match all three patterns in different ways:
 
<pre>foo<--bar:baz+xyzzy</pre>
 
The outcome will be:
 
<pre>x="foo"
y="bar:baz+xyzzy"</pre>
 
because this match minimizes the length of <code>x</code>. If we change this to <code>:longest x</code>, we get:
 
<pre>x="foo<--bar:baz"
y="xyzzy"</pre>
 
The <code>cases</code>, <code>all</code> and <code>none</code> directives most resemble control structures because they have short-circuiting behavior. For instance:
 
<lang txr>@(all)
@x:y@
@z<-@w
@(and)
@(output)
We have a match: (x, y, z, w) = (@x, @y, @z, @w).
@(end)
@(end)</lang>
 
If any subclause fails to match, then <code>all</code> stops processing subsequent clauses. There are subtleties though, because an earlier clause can produce variable bindings which are visible to later clauses. If previously bound variable is bound again, it must be to an identical piece of text:
 
<lang txr>@# match a line which contains some piece of text x
@# after the rightmost occurence of : such that the same piece
@# of text also occurs at the start of the line preceded by -->
@(all)
@*junk:@x
@(and)
-->@x@/.*/
@(end)</lang>
 
<pre>$ echo "-->asdfhjig:asdf" | txr weird.txr -
junk="-->asdfhjig"
x="asdf"
$ echo "-->assfhjig:asdf" | txr weird.txr -
false
$</pre>
 
=={{header|UNIX Shell}}==
Anonymous user