Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating factorial using Lisp

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!

like image 214
Amir Jalilifard Avatar asked Apr 18 '15 20:04

Amir Jalilifard


2 Answers

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.

like image 141
Oso Avatar answered Nov 09 '22 08:11

Oso


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.

like image 3
David Brabant Avatar answered Nov 09 '22 08:11

David Brabant