added
[rrq/newlisp/misc.git] / foop.lsp
1 ;; This newlisp module provides FOOP modelling support
2 ;;
3 ;; Functional Object-Oriented Programming (FOOP) is an abstraction
4 ;; overlay using the newlisp context notion as similar to the class
5 ;; notion in genuine object-oriented programming languages. This is
6 ;; set out in newlisp by means of the representation principle that an
7 ;; instance of a FOOP "class" (i.e. context) is a list headed by the
8 ;; context itself, and followed by the "member values".
9 ;;
10 ;; FOOP further includes by the "method invocation" syntax where a
11 ;; function is preceded by ':' and then followed by the instance
12 ;; concerned before actual function arguments. That instance is then
13 ;; stoved away as implicitly available via the (self) function, and
14 ;; the member values accessible via index, e.g. the term (self 3)
15 ;; refers to the third member of the instance. The self references are
16 ;; destructively assignable with setf.
17 ;;
18 ;; This modelling support adds member name declaration together with
19 ;; automatic getter and setter defintions. The (FOOP ...) term is used
20 ;; for declaring member names in order. For example:
21 ;;
22 ;; (context 'MAIN:EX")
23 ;; (FOOP a b c)
24 ;; (define (EX:EX n) (list (context) (+ n 4) 3 2))
25 ;;
26 ;; That would declare a FOOP context EX with instances having three
27 ;; members named a, b and c. The declaratin results in a variable EX:.
28 ;; whose value is (FOOP a b c), as well as three access functions for
29 ;; each member: the member position index (.member), a getter
30 ;; (%member) and a setter (!member V).
31 ;;
32 ;; As indicated in the example, (FOOP a b c) does not define the
33 ;; "constructor". It only defines the access functions. 
34
35 (context 'FOOP)
36
37 ;; Helper function to make a new symbol for the context of S by
38 ;; preceeding it with string P.
39 (define (name P S) (sym (string P (term S)) (prefix S)))
40
41 ;; (FOOP name ...)
42 ; foop is a language extension to declare the field names of a FOOP
43 ; object type, and thereby gain getter and setter functions with the
44 ; naming formats (:%name obj) and (:!name obj value) respectively .
45 (define-macro (FOOP:FOOP)
46   (let ((K (sym "." (prefix (first (args)))))
47         (V (cons (context) (args)))
48         (I 0))
49     (set K V)
50     (dolist (S (args))
51       (letex ((GET (name "%" S))
52               (SET (name "!" S))
53               (IT (name "." S))
54               (V (sym "V" (prefix S)))
55               (I (inc I)))
56         (define (IT) I)
57         (define (GET) (self I))
58         (define (SET V) (setf (self I) V))))
59     ))
60
61 "foop.lsp"