4 ms·
If, like me, you had some trouble wrapping your head around how the conditional operator ?: was being parsed, it may be more apparent while looking at the equiv
by groovy2shoes 12y ago
If, like me, you had some trouble wrapping your head around how the conditional operator ?: was being parsed, it may be more apparent while looking at the equivalent Scheme:
> (define initial 'J)
> (define name (if (if (if (if (eq? initial 'M)
'Mike
(eq? initial 'J))
'John
(eq? initial 'C))
'Catherine
(eq? initial 'T))
'Thomas
'unknown))
> name
Thomas
Notice that the "then" clause and the "else" clause have two different types for all but the outermost if. The "then" clause is a symbol, while the "else" clause is a boolean. Furthermore, if the "then" clause is taken, the resulting symbol is considered truthy by the if operator. So, the innermost if expression evaluates to true, then, moving outward, we get 'John (which is truthy), then we get 'Catherine (which is also truthy), then finally we get 'Thomas, which is bound to name.
PHP's truthiness rules are different from Scheme's (and are far more complicated), but for this particular expression, the net result is the same.
For comparison, every other language with a ?: operator behaves like this:
> (define nom (if (eq? initial 'M)
'Mike
(if (eq? initial 'J)
'John
(if (eq? initial 'C)
'Catherine
(if (eq? initial 'T)
'Thomas
'unknown)))))
> nom
John
Which is far more useful.