#| |# #| KSAJ'S LISP THINGS |# #| |# ; If you use any of the code I put here, I would prefer credit is given. Just my initials KSAJ is fine. I share them because Lisp is cool, and maybe these snippets will be useful to someone. I won't be posting code that is readily available elsewhere, so everything here has some type of nice quirk to them. ; Until I get around to organizing a site, here are a few nice snippets to start with. Later I'll make a writeup describing how they (and other snippets I add) work. ; Everybody's got their version of how to calculate factorials in Lisp. Here's mine. (defun factorial (a &optional (fact 1)) "Calculate factorial. Optional second arg for multifactorial." (cond ((< 0) (format t "Factorial of < 0 is not defined")) (t (reduce #'* (loop for i from a downto 1 by fact collect i))))) ; For regular factorials like 6!, you just call (factorial 6), which is the same as (factorial 6 1). This version also does multifactorials. For example, 6!!!! can be calculated with (factorial 6 4). ; If you are looking for a super-fast way to calculate the nth Fibonacci number, here is a method that doesn't use any form of looping or recursion whatsoever. It took a while to code it because I got the idea by translating Mathematical Notation, and then introduced a few shortcuts. Its workings are definitely non-obvious. ; It looks way simpler than it actually is. (defun fib-nth (n) "KSAJ's interesting way to calculate nth Fibonacci number." (logand (truncate (ash 4 (* n (+ 3 n))) (- (ash 4 (* 2 n)) (ash 2 n) 1)) (- (ash 2 n) 1))) ; I hope to share some of my Lispy ideas here. I'm still trying to feel my way around SDF.org so it might take a while.