_if
Choose what to produce, as directed --
Function
Anything -> _if
(predicate, iftrue, iffalse, asList) -> The same Type
- Receives
- Anything -- this will be passed into the predicate for testing
- predicate
- The question we're asking -- is this value true?
- iftrue
- What to produce if the predicate is true
- iffalse (optional)
- What to produce if the predicate isn't true
- asList (optional)
- Whether to treat the context as a whole, or as individual elements
- Produces
- The result from
iftrue
if the predicate
was true, iffalse
(or nothing) otherwise
_if is one of the basic building blocks of programming. It applies the received value to the
predicate
. If the result is non-empty and is true, it applies the received value to iftrue
. Otherwise,
if there is an iffalse
parameter, it applies the received value to that. (If there is no iffalse
, it
just produces the empty value.)
For example, take this expression:
[[My List -> _if(_isEmpty, ""Empty"", ""Full"")]]
If My List
is empty, this will print "Empty"; if not, it will print "Full".
This is also an easy way to test TrueOrFalse flags. Say that our Space represents a library, and we
want to print out whether a given book has the Checked Out
flag set on it. We would say:
[[My Book -> _if(Checked Out, ""Checked Out"")]]
So if My Book -> Checked Out
is true, it will print "Checked Out". Since we didn't give an
iffalse
parameter, it doesn't print anything if the Checked Out
flag isn't set.
Note that, if predicate
is empty, or the wrong type, that is treated as "false". If you're getting false
answers and don't understand why, check what your predicate
is actually producing.
The syntax of _if is likely to evolve in the future, to something more like most programming languages. For now,
though, note that iftrue
and iffalse
are inside the parentheses, rather than after them as most languages
have it.
Normally, _if
processes the received context one element at a time: it checks the predicate against
each element, and produces either the true or false path depending on the result of the predicate. But
if you set the asList
parameter to true, then it will run the predicate against the entire context
at once, and do the true or false path on the entire context. This is appropriate if you are doing
something with the whole list, like checking _isEmpty
.
(Note: setting asList
to true produces
exactly the same result as putting an asterisk before the _if
. An asterisk before a function
means "do this to the entire List, not one at a time". The asList
parameter is provided as an
alternative in this common case, though, if you find it clearer.)