LISP Triangle Numbers

To calculate the Triangular Numbers in LISP.

N = 1+2+3+...+N
T(n) = 1     if n=1
T(n) = n + T(n-1)     if n>1
T(n) = 0    if n<=0

USING IF

(defun triangle(N)
    (if (= N 1) 1 (+ N (triangle(- N 1))))
)

IF is not good for more than one condition


USING COND

(defun tri-cond(number)
    (cond ((<= number 0) 0)
              ((= number 1) 1)
              ((> number 1) (+ number (tri-cond(- number 1))))
    )
)

USING COND WITHOUT A LAST CONDITION

(defun tri-cond(number)
          (cond ((<= number 0) 0)
          ((= number 1) 1)
          ((+ number (tri-cond(- number 1))))
    )
)

Comments