summaryrefslogtreecommitdiff
path: root/example.lisp
blob: d35c314623eaae747331fed86fdf5a017031db18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
(defpackage #:mulk.protocols-examples
  (:nicknames #:protocols-examples)
  (:use #:cl #:protocols))


(in-package #:mulk.protocols-examples)


(define-protocol printable ()
  ((print-object * stream))
  (:strictness t))

(define-protocol serialisable ()
  ((serialise * stream))
  (:strictness t))

(define-protocol additive ()
  ((add * *)
   (negate *)))

(define-protocol multiplicative ()
  ((multiply * *)
   (invert *)))

(define-protocol field (additive multiplicative) ())

(define-protocol serialisable-field (serialisable field) ())


(defgeneric serialise (x stream))
(defgeneric add (x y))
(defgeneric negate (x))
(defgeneric multiply (x stream))
(defgeneric invert (x))


(defclass a () ())

;; The following should signal five style warnings about missing methods.
(implement-protocols a (serialisable-field))


(defclass b () ())

;; Note the two style warnings signalled by the following.
(implement-protocols b (additive multiplicative serialisable)
  (defmethod add ((x b) (y b)))
  (defmethod negate ((x b)))
  (defmethod multiply ((x b) y)))

(print (conforms-to-p 'b 'additive))              ;=> T
(print (really-conforms-to-p 'b 'additive))       ;=> T
(print (conforms-to-p 'b 'multiplicative))        ;=> T
(print (really-conforms-to-p 'b 'multiplicative)) ;=> NIL
(print (conforms-to-p 'b 'printable))             ;=> NIL
(print (really-conforms-to-p 'b 'printable))      ;=> NIL

;; The following works because PRINT-OBJECT is specialised over T.
(implement-protocols b (printable))

(print (conforms-to-p 'b 'printable))             ;=> T
(print (really-conforms-to-p 'b 'printable))      ;=> T

(print (subtypep 'b 'printable))                  ;=> T
(print (subtypep 'b 'additive))                   ;=> T
(print (subtypep 'b 'serialisable))               ;=> NIL

;; Protocols by default inherit their direct ancestors' strictness,
;; where NIL is recessive, while T is dominant.  In any case, a
;; strictness default can be overridden by providing the :STRICTNESS
;; option explicitely.
(print (subtypep 'a 'field))                      ;=> T
(print (subtypep 'a 'serialisable))               ;=> NIL
(print (subtypep 'a 'serialisable-field))         ;=> NIL