User Tools

Site Tools


alisp:code_examples

Here are some ALisp code examples:

Data types (with quote apostrophe where necessary to prevent evaluation):

Pair: '(1 . 2) 
List: '(1 2 3) == (1 . (2 . (3 . ())))
Improper list: '(1 2 . 3) == (1 . (2 . 3))
Vector: #(1 2 3)
String: "1 2 3"
Symbol: 'FrontierSpace
Integer: 1
Float: .3

Basic functional programming:

  (+ 1 2 3) == 6
  (* (+ 2 4) 3) == 18
  (let ((x 1) (y 2)) (list x y)) == (1 2)
  (define f (lambda (x) (* x x x))) == f
  (f 3) == 27
  (define g (lambda (&rest args) (length args))) == g
  (g 1 2 3) == 3
  (member 2 '(1 2 3)) == (2 3)

Recursive programming:

  (define fact (lambda (x)
    (cond ((<= x 1) 1)
          (#t (* x (fact (- x 1))))))) == fact
  (fact 4) == 24

Macros:

  (define ifelse (macro test tcode &opt fcode)
    `(cond (,test ,tcode)
           (#t ,fcode)))) == ifelse
  (define value #f) == value
  (ifelse #t
    (set value "True")
    (set value "False")) == value
  value == "True"
  (define when (macro (test &rest body)
    `(cond (,test ,@body))) == when
  (when #t
    (set value "Unknown")
    (set value "Done")) == value
  value == "Done"

Lexical closures:

  (let ((x 0))
    (define inc (lambda () (set x (+ x 1)) x))
    (define rst (lambda () (set x 0) x))) == rst
  (inc) == 1
  (inc) == 2
  (rst) == 0
  (inc) == 1
  x == Exception: Undefined symbol

The map operator:

  (map length '(() #(1 2) (3 4 5))) == (0 2 3)
  (map (lambda (x) (apply + x)) '(() (2 3) (5 7 9))) == (0 5 21)

The compiler:

  (define f-interpreted (lambda (x) (* x x))) == f-interpreted
  f-interpreted == #<closure (x)>
  (define f (compile f-interpreted)) == f
  f == #<compiled-closure anonymous (1)>
  (define f (compile f-interpreted 'f)) == f
  f == #<compiled-closure f (1)>
  (format "~I" (disassemble f)) ==
  "((create-frame 1)
    (load-argument 0)
    (save-to-frame 0)
    (create-argument-vector 2)
    (load-from-frame 0)
    (save-to-argument-vector 0)
    (load-from-frame 0)
    (save-to-argument-vector 1)
    (load-object #<procedure * (...)>)
    (apply)
    (free-argument-vector))"
  (define g-interpreted (lambda (x) (lambda (y) (+ x y)))) == g-interpreted
  (g-interpreted 0) == #<closure (y)>
  (define g (compile g-interpreted 'g)) == g
  (g 0) == #<compiled-closure anonymous (1)>
alisp/code_examples.txt · Last modified: 2018/06/23 00:30 (external edit)