Anonymous user
Short-circuit evaluation: Difference between revisions
→Icon and Unicon
(→{{header|Icon}}: better example) |
|||
Line 118:
</pre>
== Icon and Unicon ==
The entire concept of using 'boolean' values for logic control runs counter to the philosophy of Icon. Instead Icon has success (something that returns a result) and failure which is really a signal. The concept is similar to that used in [[:Category:SNOBOL4|SNOBOL4]] and [[:Category:Lisp|Lisp]] and far more potent than passing around and testing booleans. There is no way to pass around a 'false' value in that sense. Because failure is a signal control is always evaluated in a short-circuit manner. One consequence of this is that an expression "i < j" doesn't return a boolean value, instead it returns the value of j. While this may seem odd at first it allows for elegant expressions like "i < j < k".
While this task could be written literally, it would be more beneficial to show how an Icon programmer would approach the same problem. Icon
* Since any result means an expression succeeded and is hence true, we can use any value. In this example our choice will be determined by how we deal with 'false'.
*
* For this example we will define two procedures 'true' and 'false'. Because Icon treats procedures as a data type we can assign them and invoke them indirectly via the variable name they are assigned to. We can write " i := true " and later invoke 'true' this via " i() ".
* Rather than have the tasks print their own name, we will just utilize built-in tracing which will be more informative.
This use of procedures as values is somewhat contrived but serves us well for demonstration.
==={{header|Icon}}===
<lang Icon>procedure main()
Line 139 ⟶ 141:
end
procedure true() #: succeeds always (returning null)
return
end
procedure false() #: fails always
fail # for clarity but not needed as running into end has the same effect
end
</lang>
|