;;; -*- scheme -*- ;;; $Id: test.l,v 1.2 2001-05-31 14:27:21-05 annis Exp annis $ ;;; Testing of some basic lisp code. ;;; Does the read() method work? (def foo (lambda (x y) (* x y))) (print (foo 12 55)) (def square (lambda (x) (* x x))) ;;; recursion tests (def map (lambda (fn args) (if (null? args) '() (cons (fn (first args)) (map fn (rest args)))))) (print (map square '(2 4 5 7))) (def member (lambda (elt lst) (cond ((null? lst) *false*) ((== elt (first lst)) elt) (*true* (member elt (rest lst)))))) (print (member 'c '(a b c d))) (print (member 'd '(a b c d))) (print (member 'e '(a b c d))) ;;; If you like a more common-lisp flavor for functions: ;;; (defun square (x) (* x x)) (def defun (macro (name args body) `(def ,name (lambda ,args ,body)))) ;;; Perhaps you like an official scheme version of define which can do ;;; two things? (def define (macro (head tail) (if (list? head) ; (define (square x) (* x x)) `(def ,(car head) (lambda ,(rest head) (begin ,tail))) ; (define foo 12) `(def ,head ,tail)))) ;;; Let's see what this does... (print (macro-expand (define foo 12))) (print (macro-expand (define (square x) (* x x)))) ;;; Redefine the list function with &rest arguments: (def list (lambda (&rest l) l)) ;;; Maybe you want to write your own interpreter: (def eval (macro (code) `(begin ,@code))) ;;; This could be: ;;; (macro (code) `,code) but that exercises a parsing buglet right now. ;;; A trivial apply: (apply + (2 5)). Works with macros, too, which is odd. (def apply (macro (fn args) `(,fn ,@args))) (def incf (macro (x) `(setq ,x (+ ,x 1)))) (def bob 33) (print 'bob bob) (apply incf (bob)) (print 'bob bob) (print (apply square (bob))) ;;; Various bits of scoping cleverness are also possible: (def make-value (lambda (value) (let ((dispatch (lambda (message) (cond ((== message 'get) (lambda () value)) ((== message 'set) (lambda (new-value) (setq value new-value))) (*true* 'unknown-message!))))) dispatch))) (def bob (make-value 14)) ((bob 'get)) ((bob 'set) 42) ((bob 'get)) ;;; Always fun: Fibonacci sequence: (def fib (lambda (x) (if (< x 2) x (+ (fib (- x 1)) (fib (- x 2)))))) (print "doing (fib 15) - this will be slow...") (print "The answer should be 610. It is:" (fib 15))