4 ms·
`if` has two distinguishing features: - It selects between two possibilities - The non-selected possibility isn't evaluated/executed (i.e. the evaluation of t
by chriswarbo 8y ago
`if` has two distinguishing features:
- It selects between two possibilities
- The non-selected possibility isn't evaluated/executed (i.e. the evaluation of the possibilities is delayed until after one has been selected)
This is very important for imperative languages, since executing both branches would have observable effects even if we only returned one result.
This is also true in functional programming languages, even pure ones, since it's needed to e.g. terminate recursive calls. For example, if we define factorial by branching on whether the argument is 0 (base case) or not (recursive case), then evaluating both branches before selecting one would cause an infinite recursion for all arguments.
In the case of your Lisp code, we couldn't implement a recursive function like factorial unless we delay the evaluation e.g. by using macros to do the selection, or by switching from Lisp's default evaluation order (call-by-value) to something non-eager like call-by-name or call-by-need.