My implementation for factorial in Lisp. This is a response to a post found here.

Also, it is tail recursive.


(defun fact (n)
       (labels ((rec (n acc)
           (if (< n 2)
           acc
           (rec (1- n ) (* acc n)))))
         (rec n 1)))

ps: Factorial in Haskell seems easier though


fact 0 = 1
fact n = n * fact (n-1)

or


fact = product . enumFromTo 1

Edit: fixed the (< n 1) bug

One Comment

  1. I realize that you wrote this a while ago, but there is a bug in your Lisp version of factorial function. If you call (factorial 0), I believe you get an infinite loop. I think that the “if” condition should be (if (<= n 1) …) to fix it.


Post a Comment

*
*