I was reading a code sample that calculates the factorial using Lisp as below:
(defun fatorial (n)
(cond
((= n 1) 1)
(t (* n (fatorial (- n 1))))))
So, I was wondering what is t
in this code sample? Does it have any special meaning in Lisp? I searched but couldn't find my answer!
That's the symbol LISP uses for True. In a cond
in LISPs, the "catch all" at the end uses t
to indicate that if none of the preceding conditions evaluate to True, this code will always execute.
Consider it here as the equivalent of an else
in an if-else. On the whole, though, it just represents True.
A cond consists of the cond
symbol followed by a number of cond clauses, each of which is a list. The first element of a cond clause is the condition; the remaining elements (if any) are the action. The cond form finds the first clause whose condition evaluates to true (ie, doesn't evaluate to nil); it then executes the corresponding action and returns the resulting value.
So, in your code, the firs test checks if n equals 1 and, if so, returns 1. The other clause, starting with "t" (for true in lisp) is the "else" part of the condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With