Icon+Unicon/Intro: Difference between revisions

→‎Contractions: example in progress
(→‎Contractions: removed broken example)
(→‎Contractions: example in progress)
Line 616:
end</lang>
This is probably only lovable by J programmers.
 
=== An Ugly Example ===
 
The following procedure "IsFilled" was taken from the [[Sierpinski_carpet#Icon_and_Unicon|Sierpinski Carpet task]]:<lang Icon>procedure IsFilled(x,y). It has the benefit of being clear. It makes use of only a few natural contractions, augmented division and chaining of comparison operators.
while x ~= 0 & y ~= 0 do {
if x % 3 = y %3 = 1 then fail
x /:= 3
y /:=3
}
return
end</lang>
 
We can transform this.
 
Firstly, we can rewrite the while condition in the following ways:<lang Icon>while x ~= 0 & y ~= 0 do { # original
until not ( x ~= 0 & y ~= 0) do { # inverted
every | (0 = (x|y) & break) | &null do { # converted to an every loop (but incomplete)</lang>
 
The final transformation of a while into an ''every'' expression can be useful sometimes, but its not without challenges and can produce ugly results.
 
The failing condition can also be converted as in these examples:<lang Icon>
if x % 3 = y %3 = 1 then fail # original
( x % 3 = y %3 = 1) & fail ) | &null # converted for use with every | expr</lang>
 
The ''do'' part can be converted using conjunction.<lang Icon>
x /:= 3 # original
y /:=3 # ...
( x /:= 3 & y /:=3 ) # contracted</lang>
 
Putting these together and eliminating the trailing ''return'' in favor of the default fail at end, we get the rather odd looking:<lang Icon>procedure IsFilled("x,y)
every | ( (0 = (x|y) & return) | &null,
(( x % 3 = y %3 = 1) & break ) | &null,
( x /:= 3 & y /:=3 ) )
end</lang>
 
The alternations with &null can be eliminated by rewiring the path of alternatives with not expressions:<lang Icon>procedure IsFilled(x,y)
every | (not (0 = (x|y), return)) &
(not ( x % 3 = y %3 = 1, break )) &
( x /:= 3 & y /:=3 )
end</lang>
 
I'll resist compressing this into a one-liner.
 
The need for alternation with &null may require some explaining. Repeated alternation is defined as:
<pre> |expr repeatedly evaluates expr, producing its entire result
sequence each time, but failing if evaluation of expr results
in an empty result sequence.</pre>
 
= Run Time Considerations =
Anonymous user