Calculating factorial using Lisp
Asked Answered
E

2

6

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!

Exhortation answered 18/4, 2015 at 20:4 Comment(3)
I guess that you named your function fatorial because it results in a fat stack footprint.Pascha
Wrong guess! In Spanish, Factorial is written : Fatorial ! ;)Exhortation
What? ... In spanish, factorial is written... "factorial". Anyway, I suppose the stack always behave like this for recursion.Janayjanaya
M
8

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.

Moneyer answered 18/4, 2015 at 20:10 Comment(0)
R
3

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.

Rutaceous answered 18/4, 2015 at 20:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.