Skip to content
b-studios edited this page Oct 7, 2011 · 8 revisions

All of the following examples can be run in the online version of the lisp.js interpreter.

In the repo you can find some more advanced samples.

Greatest Common Divisor

(define gcd (lambda (x y) 
  (if (eq? y 0)
     x
  ; else
     (gcd y (% x y)))))

(gcd 12 9)
;-> 3

Factorial

(define ! (lambda (num)
  (if (lt? num 1)
    1
  ; else
    (* (! (- num 1)) num))))

Some Helper Functions

(defmacro defun (name args body) 
  '(define ,(cons name args) ,body))

(defun else (body) 
  body)
(define elsif if)  

(defun pair? (item)
  (eq? (typeof item) "Pair"))

(defun nil? (item)
  (eq? item nil))
    
(defmacro NTH (n)

; we want (car . ((cdr . ('innerst . nil)) . nil))
; (cons 'car (cons (cons 'cdr (cons 'innerst nil)) nil))

  (begin
    (define (helper m innerst)

      (if (eq? m 0)
        innerst

      ;else
        (cons 'cdr (cons (helper (- m 1) innerst) nil))))
     
    '(lambda (lst) ,(cons 'car (cons (helper (- n 1) 'lst) nil)))
   )
)

(define first (NTH 1))
(define second (NTH 2))
(define third (NTH 3))
(define fourth (NTH 4))
(define fifth (NTH 5))
(define sixth (NTH 6))
(define seventh (NTH 7))

(define new-bindings (lambda () (get-bindings)))

(define Hash (lambda ()
  (define env (new-bindings))
  (lambda (sym . args)

    ; get
    (if (eq? sym 'get)
      (let ((key (car args)))
        (eval key env))
    
    ; set
    (if (eq? sym 'set)
      (let ((key (car args))
            (val (car (cdr args))))
          (eval '(define ,key ,val) env))
          
    ; defined?
    (if (eq? sym 'defined?)
      (let ((key (car args)))
          (eval '(defined? (quote ,key)) env))
    
    ; get-binding
    (if (eq? sym 'get-binding)
      env
    
    ; else
    (error (+ "Method '" sym "' not defined"))
    
    )))))))
  
(define (each lst method)
  (if (eq? lst nil)
    nil
  ;else
    (begin
      (method (car lst))
      (each (cdr lst) method))))
Clone this wiki locally