Sample TinyLisp Programs

Below are a few sample TinyLisp programs. To use them , simply copy them into the "Lisp Input" text area of TLisp and click on the "Evaluate" button.

Fibonacci Sequence Example

;; Return the n'th Fibonacci number
(defun fib_n (n)
  (if (integerp n)
    (if (or (= n 1) (< n 1))
      1
      (+ (fib_n (+ n -1)) (fib_n (+ n -2)) ) )
    nil))

;; Return the a list of the first i Fibonacci numbers
(defun fib (i)
  (if (and (integerp i) (> i 0))
    (append (fib (+ i -1)) (list (fib_n i)) )))

;; Run the FIB function to display a list of the first 10 Fibonacci numbers
(fib 10)

;; This should be the returned result:
; (1 2 3 5 8 13 21 34 55 89)
Prime Numbers Example
;; Returns T if j divides i evenly, otherwise returns nil
(defun dividesp ( i j )
  (if (= i 0)
    T
    (if (< i 0)
      NIL
      (dividesp (+ i (* -1 j)) j))))

;; Helper function for primep
(defun primep_extra (n m)
  (if (> (* m m) n)
    T
    (if (dividesp n m)
      nil
      (primep_extra n (+ m 1)))))

;; Return T if n is a prime number, otherwise return NIL
(defun primep (n)
  (primep_extra n 2))

;; Return all prime numbers less than i
(defun primes (i)
  (if (and (integerp i) (> i 0))
    (append (primes (+ i -1))
            (if (primep i)
              (list i)
              nil) )))

;; Run primes to display all prime numbers less than 50
(primes 50)

;; This should be the returned result:
; (1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47)
Function Scoping Rules Example
;; Test of Scoping Rules
(defun f (x) (defun g (y) (+ x y)))

(f 1)
; Should return:
; G

(g 2)
; Should return:
; 3

(setq x 10)
; Should return:
; 10

(g 15)
; Should return:
; 16

Return to TLisp Interpreter main page.
For more information, send e-mail to rona@post.com or visit Ron Alterovitz's Internet Site.