-
Notifications
You must be signed in to change notification settings - Fork 2
/
cells-doc.tex
2188 lines (1498 loc) · 57.6 KB
/
cells-doc.tex
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%% LyX 1.3 created this file. For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin1]{inputenc}
\IfFileExists{url.sty}{\usepackage{url}}
{\newcommand{\url}{\texttt}}
\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.
%% Bold symbol macro for standard LaTeX users
\newcommand{\boldsymbol}[1]{\mbox{\boldmath $#1$}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
\newenvironment{lyxcode}
{\begin{list}{}{
\setlength{\rightmargin}{\leftmargin}
\setlength{\listparindent}{0pt}% needed for AMS classes
\raggedright
\setlength{\itemsep}{0pt}
\setlength{\parsep}{0pt}
\normalfont\ttfamily}%
\item[]}
{\end{list}}
\newenvironment{lyxlist}[1]
{\begin{list}{}
{\settowidth{\labelwidth}{#1}
\setlength{\leftmargin}{\labelwidth}
\addtolength{\leftmargin}{\labelsep}
\renewcommand{\makelabel}[1]{##1\hfil}}}
{\end{list}}
\usepackage{babel}
\makeatother
\begin{document}
\title{Cells tutorial}
\maketitle
\tableofcontents{}
\part{Cells}
\section{Introduction}
\subsection{What's cells?}
Cells is a Common Lisp library that extends the language, and in particular
its object system, to let you write dataflow-driven programs. What
does this mean? This means that the flow of control of the program
depends no more on the sequence of function/method calls, but on the
data. Cells lets you specify the dependence beetwen different slots%
\footnote{A slot is the Common Lisp equivalent of a class instance variable
in other languages%
} in a family of classes. Once these constraints have been registered,
the cells system will take care of them, and will recalculate a value
when some data on which it depends has changed. As a consequence,
the programmer just has to tell the system the \emph{relationship}
between the data, the burden of maintaining them true is handled automatically
by cells.
\subsection{How could it improve your programs?}
Cells may not be the panacea of programming, but it sure helps a lot
in contexts where keeping a set of values consistent is crucial. A
particular set of applications where this is important are graphical
applications%
\footnote{See the cells-gtk project: \url{http://common-lisp.net/project/cells-gtk}%
}, where you need to maintain consistency between what the user sees
and the real values held by the program in its internal data structures.
An example is the state of the 'Cut' menu entry in an editor: it is
usually clickable when the user has selected a piece of text and not
clickable in all the other cases. In a normal application, to achieve
this behavior you would need to track all the methods and all the
user actions that could modify the region of text currently being
selected, and add activate/disactivate calls in all those places to
keep the menu entry in a consistent state. With cells, you just need
to tell the system that the state of the menu depends on the length
of the current text selection: if the length is 0 then the state is
'deactivated', else it is 'activated'. Now you can safely work on
the rest of the application ignoring the state of the menu: it will
be automatically recalculated every time the length of the current
selection varies. Moreover, everything relating to the menu entry
is placed near its definition, and not scattered across different
functions/methods.
\section{Installation}
The installation is quite simple once you have a working Common Lisp
system. Here I will assume that you've got a working copy of SBCL%
\footnote{SBCL \url{http://www.sbcl.org}%
}. First of all, download cells: you can get the latest version at
\url{http://common-lisp.net/cgi-bin/viewcvs.cgi/cells/?root=cells}.
Then enter the directory \textasciitilde{}/.sbcl/site and unpack cells:
\begin{lyxcode}
\$~cd~\textasciitilde{}/.sbcl/site
\$~tar~-zxvf~\textasciitilde{}/cells.tar.gz
\end{lyxcode}
Now be sure that ASDF will be able to find it:
\begin{lyxcode}
\$~cd~\textasciitilde{}/.sbcl/systems
\$~for~a~in~`find~\textasciitilde{}/.sbcl/site/cells/~-name~{}``{*}.asdf''`~\textbackslash{}
\begin{lyxcode}
do~ln~-sf~\$a~.~\textbackslash{}
\end{lyxcode}
done
\end{lyxcode}
After that, start SBCL and evaluate the following expressions:
\begin{lyxcode}
>~(require~:asdf)
NIL
>~(asdf:oos~'asdf:load-op~:cells)
(some~output~will~follow)
\end{lyxcode}
If everything went right cells should be up and running.
\section{Our first cells program}
\subsection{The program}
Write the following piece of code in a file named hello-cells.lisp:
\begin{lyxcode}
(defmodel~hello-cells~()
~~((num~:accessor~num~:initarg~:num~:initform~(c-in~0))
~~~(square-num~:accessor~square-num~
~~~~~~~~~~~~~~~:initform~(c?~({*}~(num~self)~(num~self))))))
(defun~hello~()
~~(let~((h~(make-instance~'hello-cells)))
~~~~(dolist~(n~'(10~20~30~40~50~60~60))
~~~~~~(setf~(num~h)~n)
~~~~~~(format~t~\char`\"{}num~is~\textasciitilde{}a~and~square-num~is~\textasciitilde{}a\textasciitilde{}\%\char`\"{}~(num~h)~(square-num~h)))))
\end{lyxcode}
Now start the SBCL interpreter in the same directory and evaluate
the following:
\begin{lyxcode}
>~(asdf:oos~'asdf:load-op~:cells)
...
>~(use-package~:cells)
T
>~(load~{}``hello-cells.lisp'')
...
T
>~(hello)
num~is~10~and~square-num~is~100
num~is~20~and~square-num~is~400
num~is~30~and~square-num~is~900
num~is~40~and~square-num~is~1600
num~is~50~and~square-num~is~2500
num~is~60~and~square-num~is~3600
num~is~60~and~square-num~is~3600
NIL
\end{lyxcode}
What happens within the function 'hello'? First, an object of type
hello-cells is created. After that the program iterates over the contents
of the list '(10 20 30 40 50 60 60), and every number is used to set
the num slot of the object h. Then the num slot is printed together
with the slot square-num. The printed value of the slot num gives
us no surprise: it has the value we gave it. This doesn't hold for
the slot square-num, though: we never gave it a value within the loop,
but it always holds the square of the slot num! This is just cells
working for us: we told the system that the relation
\begin{lyxcode}
$num*num=squarenum$
\end{lyxcode}
must hold, and every time num changes, the expression ({*} (num self)
(num self)) is re-evaluated. Note that the relation isn't a mathematical
equation: you can't change square-num and expect to find its square
root in num.
\subsection{The program line-by-line}
Lets now analyze the program. The very first line uses the construct
defmodel:
\begin{lyxcode}
(defmodel~hello-cells~()
\end{lyxcode}
defmodel is very similar to defclass and everything valid in a defclass
construct is valid within defmodel%
\footnote{defmodel is a layer built on top of defclass%
}. The main difference is that all the slots defined within it will
be tracked by cells, except slots that are explicitly declared to
be ignored by the system by specifying :cell nil in the definition.
\begin{lyxcode}
((num~:accessor~num~:initarg~:num~:initform~(c-in~0))
\end{lyxcode}
Here we define the slot num as we would do within a standard class
declaration. The difference is in its initialization expression: instead
of the number 0 we have (c-in 0). Why? (c-in <expr>) is a construct
that tells cells that the value of num may be changed, so whenever
it does change a re-evaluation of all the slots that depend on it
must be triggered. If we did just write 0 instead of (c-in 0) a runtime
error would have been raised during the execution of (setf (num h)
...). So, when a slot is writable it must be signalled to cells with
the (c-in ...) construct. This is necessary to let cells do some optimizations
like avoiding to remember dependencies on slots that will never change.
Slots initialized with c-in are usually called {}``input cells''.
\begin{lyxcode}
(square-num~:accessor~square-num~
~~~~~~~~~~~~:initform~(c?~({*}~(num~self)~(num~self))))))
\end{lyxcode}
Now we define the slot square-num. There are two things to note here:
(c? <expr>) and 'self'.The first is a construct that says: {}``To
calculate the value of square-num, evaluate the expression <expr>''.
Within (c? ...) the variable self is bound to the object itself. (c?
...) automatically tracks any dependency, in this case the dependency
on the value of num: when num changes, ({*} (num self) (num self))
will be re-evaluated. Slots initialized with c? are called {}``ruled
cells''.
\begin{lyxcode}
(let~((h~(make-instance~'hello-cells)))
\end{lyxcode}
Here we use the function (make-instance <model-name> \emph{args{*}}),
to create an object of type <model-name>, in this case hello-cells,
as we would do to instantiate a normal class. You could specify an
initial value for num now:
\begin{lyxcode}
(let~((h~(make-instance~'hello-cells~:num~(c-in~50))))
\end{lyxcode}
Note that you \emph{must} repeat the (c-in ...) construct. This is
because the behavior of the slot (input cell, constant, ruled cell)
is decided on a per instance basis, not on a per class basis. This
means that, in our example, we could have two objects of type hello-cells,
one where the slot num is settable and one where it is has a constant
value. When an object is created, all the values of its slots are
computed for the first time, in this case the expression ({*} (num
self) (num self)) is evaluated and the value given to the slot square-num.
\begin{lyxcode}
(setf~(num~h)~n)
\end{lyxcode}
This expression sets the value of the slot num to n. This is when
cells comes into action: square-num depends on num, so ({*} (num self)
(num self)) is re-evaluated after n has changed.
\begin{lyxcode}
(format~t~\char`\"{}num~is~\textasciitilde{}a~and~square-num~is~\textasciitilde{}a\textasciitilde{}\%\char`\"{}~(num~h)~(square-num~h))
\end{lyxcode}
Finally, we print the values of the two slots and discover that the
value of square-num is correctly the square of num.
As a side note, you can reset the cells system by calling (cell-reset):
\begin{lyxcode}
>~(cells-reset)
NIL
\end{lyxcode}
This could be necessary after an error has corrupted the system and
cells doesn't seem to work correctly anymore. It's also a good practice
to reset the system before running code that uses cells.
\section{The family system}
Objects whose type have been defined using defmodel can be organized
in families. A family is a tree of model instances (\emph{not} of
model classes!) that can reference each other using the functions
(fm-other ...), (fm\textasciicircum{} ...) and others. You can specify
the family tree at object creation time passing a list of children
to the argument :kids. Alternatively, you can access the slot .kids
(automatically created by defmodel) and set it at runtime to change
the family components. .kids is, by default, a slot of type c-in,
and you can access it through the method (kids object). You can change
the .kids slot to be of a type other than c-in as you could do with
any other slot. To access the members of a family you can give them
a name with the argument :md-name and then reference them by their
name. Another way to access them is through their type: you could
say, for example, {}``give me all the successors of type my-type''.
To use these features your models must inherit from the model 'family'.
Models that inherit from family have also a .value slot associated,
which you can access through the method (value self)%
\footnote{In older releases of cells you had to use (md-value self) instead%
}. The following example shows some of these things in action:
\begin{lyxcode}
(defmodel~node~(family)
~~((val~:initform~(c-in~nil)~:initarg~:val)))
(defun~math-op-family~()
~~(let~((root
~~~~~~~~~(make-instance
~~~~~~~~~~'node
~~~~~~~~~~:val~(c?~(apply~\#'+~(mapcar~\#'val~(kids~self))))
~~~~~~~~~~:kids
~~~~~~~~~~(c?
~~~~~~~~~~~~(the-kids
~~~~~~~~~~~~~~(make-kid~'node~:md-name~:n5~:val~(c-in~5))
~~~~~~~~~~~~~~(make-kid
~~~~~~~~~~~~~~~'node
~~~~~~~~~~~~~~~:val~(c?~(apply~\#'{*}~(mapcar~\#'val~(kids~self))))
~~~~~~~~~~~~~~~:kids
~~~~~~~~~~~~~~~(c?
~~~~~~~~~~~~~~~~~(the-kids
~~~~~~~~~~~~~~~~~~(make-kid~'node~:md-name~:n7~:val~(c-in~7))
~~~~~~~~~~~~~~~~~~(make-kid~'node~:md-name~:n9~:val~(c-in~9))))))))))~~~
~~~~(format~t~\char`\"{}value~of~the~tree~is~\textasciitilde{}a\textasciitilde{}\%\char`\"{}~(val~root))
~~~~(setf~(val~(fm-other~:n7~:starting~root))~10)
~~~~(format~t~\char`\"{}new~value~of~the~tree~is~\textasciitilde{}a\textasciitilde{}\%\char`\"{}~(val~root))))~
\end{lyxcode}
Write it in a file (in this case hello-cells.lisp) and load it:
\begin{lyxcode}
>~(load~{}``hello-cells.lisp'')
T
>~(math-op-family)
value~of~the~tree~is~68
new~value~of~the~tree~is~95
NIL
\end{lyxcode}
Lets' see the most important parts of the program:
\begin{lyxcode}
(defmodel~node~(family)
~~((val~:initform~(c-in~nil)~:initarg~:val)))
\end{lyxcode}
Here we define the model node: we plan to build a family of nodes,
so we inherit from the model family. The slot val will contain the
value of the node.
\begin{lyxcode}
(make-instance~
~'node
~:val~(c?~(apply~\#'+~(mapcar~\#'val~(kids~self))))
\end{lyxcode}
Now we create the main node: its value is defined as the sum of all
its children values. To get the children list we use the method (kids
self).
\begin{lyxcode}
:kids
(c?
~~(the-kids
\end{lyxcode}
We specify the children list using the :kids argument. the-kids builds
a list of children using the following arguments. the-kids also removes
nil kids and if an argument is a list then it is flattened, e.g. (the-kids
(list k1 (list (list k2 nil) k3))) will return a list with the kids
k1, k2 and k3.
\begin{lyxcode}
(make-kid~'node~:md-name~:n5~:val~(c-in~5))
\end{lyxcode}
This is the first child of the main node: we give it a name with the
:md-name argument to reference the node through it in the future.
To create an instance of a model intended to be a child you must specify
to make-instance its parent through the argument :fm-parent. make-kid
does this for us passing self as the parent.
\begin{lyxcode}
(make-kid
~'node
~:val~(c?~(apply~\#'{*}~(mapcar~\#'val~(kids~self))))
~:kids
~(c?
~~~(the-kids
~~~~~(make-kid~'node~:md-name~:n7~:val~(c-in~7))
~~~~~(make-kid~'node~:md-name~:n9~:val~(c-in~9)))))
\end{lyxcode}
The second child of the main node has two children and its value is
the product of their values.
\begin{lyxcode}
(format~t~\char`\"{}value~of~the~tree~is~\textasciitilde{}a\textasciitilde{}\%\char`\"{}~(val~root))
(setf~(val~(fm-other~:n7~:starting~root))~10)
(format~t~\char`\"{}new~value~of~the~tree~is~\textasciitilde{}a\textasciitilde{}\%\char`\"{}~(val~root))))
\end{lyxcode}
The body of the function prints the value of the tree, and through
the output you can see that it depends correctly on the values of
its children. Then we change the value of the node named :n7 and see
that the new output has changed accordingly. (fm-other <member-name>
<starting-point>) searches the family tree starting from <starting-point>,
and returns the object named <member-name>. If it is not found, and
error is raised. <starting-point> is optional, and it defaults to
'self'. We used fm-other outside of a defmodel, so there is no self
and we must supply a starting point.
\section{Defining an observer}
Cells lets you define a function to execute immediately after a c-in
slot is modified. This function is called an {}``observer''. To
define it, use the defobserver construct:
\begin{lyxcode}
(defobserver~<slot-name>~(\&optional~(<self>~self)~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(<new-value>~old-value)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(<old-value>~new-value)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(<old-value-boundp>~old-value-boundp))
~~<function-body>)
\end{lyxcode}
This function will be executed every time the slot <slot-name> of
an object of type <model-name> is modified. <old-value> will hold
the previous value of the slot, <new-value> the new one and <old-value-boundp>
will be nil if this is the first time the slot gets a value and t
otherwise. If not given, <self>, <new-value>, <old-value> and <old-value-boundp>
will default to 'self', 'new-value', 'old-value' and 'old-value-bound-p'.
In older releases of cells defobserver was called def-c-output.
Suppose we want to log all the values that the num slot assumes: we
can do this defining an observer function. Add the following lines
to hello-cells.lisp:
\begin{lyxcode}
(defobserver~num~((self~hello-cells))
~~(format~t~{}``new~value~of~num~is:~\textasciitilde{}a\textasciitilde{}\%''~new-value))
\end{lyxcode}
Now reload the file and try running (hello) again:
\begin{lyxcode}
>~(load~{}``hello-cells.lisp'')
T
>~(hello)
new~value~of~num~is:~0
new~value~of~num~is:~10
num~is~10~and~square-num~is~100
new~value~of~num~is:~20
num~is~20~and~square-num~is~400
new~value~of~num~is:~30
num~is~30~and~square-num~is~900
new~value~of~num~is:~40
num~is~40~and~square-num~is~1600
new~value~of~num~is:~50
num~is~50~and~square-num~is~2500
new~value~of~num~is:~60
num~is~60~and~square-num~is~3600~
num~is~60~and~square-num~is~3600
NIL
\end{lyxcode}
As you can see from the output, every time we set (num h) with a different
value, the action previously defined is called. This also happens
when (num h) is initialized for the first time at object creation
time. You may have noted that when we set (num h) to 60 for the second
time, the observer function isn't called: this is because when you
set a slot to a new value that is the same (according to the function
eql) as its old one, the change isn't propagated because there is
no need to propagate it: it didn't change!
Now look at the following piece of code:
\begin{lyxcode}
(defmodel~str-model~()
~~((str~:accessor~str~:initform~(c-in~\char`\"{}\char`\"{})~:initarg~:str)
~~~(rev-str~:accessor~rev-str~:initform~(c?~(reverse~(str~self))))))
(defobserver~str~()
~~(format~t~\char`\"{}changed!\textasciitilde{}\%\char`\"{}))
(defun~try-str-model~()
~~(let~((s~(make-instance~'str-model)))
~~~~(dolist~(l~`(\char`\"{}Hello!\char`\"{}~\char`\"{}Bye\char`\"{}~
~~~~~~~~~~~~~~~~~,(concatenate~'string~\char`\"{}By\char`\"{}~\char`\"{}e\char`\"{})~\char`\"{}!olleH\char`\"{}))
~~~~~~(setf~(str~s)~l)
~~~~~~(format~t~\char`\"{}str~is~\textbackslash{}\char`\"{}\textasciitilde{}a\textbackslash{}\char`\"{},~rev-str~is~\textbackslash{}\char`\"{}\textasciitilde{}a\textbackslash{}\char`\"{}\textasciitilde{}\%\char`\"{}~
~~~~~~~~~~~~~~(str~s)~(rev-str~s)))))
\end{lyxcode}
It does nothing new: it constrains rev-str to be the reverse of str,
creates an instance of str-model and prints some strings together
with their reverse. It also logs every time it needs to compute the
reversed string. Note that the second and the third strings of the
list are actually equal. Lets try to run the code (supposing you wrote
it in hello-cells.lisp):
\begin{lyxcode}
>~(load~{}``hello-cells.lisp'')
T
>~(try-str-model)
changed!
changed!
str~is~\char`\"{}Hello!\char`\"{},~rev-str~is~\char`\"{}!olleH\char`\"{}
changed!
str~is~\char`\"{}Bye\char`\"{},~rev-str~is~\char`\"{}eyB\char`\"{}
changed!
str~is~\char`\"{}Bye\char`\"{},~rev-str~is~\char`\"{}eyB\char`\"{}
changed!
str~is~\char`\"{}!olleH\char`\"{},~rev-str~is~\char`\"{}Hello!\char`\"{}
NIL
\end{lyxcode}
The reversed string is calculated \emph{every} time we set (str s),
even when we're changing it from {}``Bye'' to {}``Bye''. But {}``Bye''
and {}``Bye'' are equal! Why do we need to waste time reversing
it twice? Because cells by default uses eql to test for equality and
if two strings aren't the same string (i.e. they don't have the same
memory address) eql considers them to be different. The following
piece of code shows us another problem: suppose we change
\begin{lyxcode}
`(\char`\"{}Hello!\char`\"{}~\char`\"{}Bye\char`\"{}~,(concatenate~'string~\char`\"{}By\char`\"{}~\char`\"{}e\char`\"{})~\char`\"{}!olleH\char`\"{})
\end{lyxcode}
to
\begin{lyxcode}
`(\char`\"{}Hello!\char`\"{}~\char`\"{}Bye\char`\"{}~\char`\"{}Bye\char`\"{}~\char`\"{}!olleH\char`\"{})
\end{lyxcode}
depending on the Common Lisp implementation you run the program on
you'll have a different output! Solving the problem is easy, we just
need to use equal instead of eql as the equality function. To supply
your own equality function pass it to the :unchanged-if argument in
the slot definition:
\begin{lyxcode}
(str~:accessor~str~:initform~(c-in~\char`\"{}\char`\"{})~:initarg~:str~
~~~~~:unchanged-if~\#'equal)
\end{lyxcode}
Now we get the same expected result on any implementation:
\begin{lyxcode}
changed!
changed!
str~is~\char`\"{}Hello!\char`\"{},~rev-str~is~\char`\"{}!olleH\char`\"{}
changed!
str~is~\char`\"{}Bye\char`\"{},~rev-str~is~\char`\"{}eyB\char`\"{}
str~is~\char`\"{}Bye\char`\"{},~rev-str~is~\char`\"{}eyB\char`\"{}
changed!
str~is~\char`\"{}!olleH\char`\"{},~rev-str~is~\char`\"{}Hello!\char`\"{}
NIL
\end{lyxcode}
The equality function must accept two values: the new value of the
slot and the old one.
\section{Lazy cells}
Ruled cells are evaluated, as we have already seen, at instance creation
time and after dependent cells change. However, you may want to \emph{not}
evaluate a ruled cell until it is really needed, i.e. when the program
asks for its value. To achieve such a behavior, you can use lazy cells.
There are three types of them, depending on their laziness:
\begin{enumerate}
\item :once-asked this will get evaluated/observed on initialization, but
won't be reevaluated immediately if dependencies change, rather only
when read by application code.
\item :until-asked this does not get evaluated/observed until read by application
code, but then it becomes un-lazy, eagerly re-evaluated as soon as
any dependency changes (not waiting until asked).
\item :always this isn't evaluated/observed until read, and not reevaluated
until read after a dependency changes.
\end{enumerate}
There are two ways in which a cell can be lazy: by not being evaluated
immediately after its creation and by not responding to dependencies
change. In both cases, when the program asks for its value, the lazy
cell is evaluated (if needed). The first type embodies only the second
way, the second type only the first way and the third type is lazy
in both ways. The following example shows the behavior of lazy cells:
\begin{lyxcode}
(defmodel~lazy-test~()
~~((lazy-1~:accessor~lazy-1~:initform~(c-formula~(:lazy~:once-asked)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~(append~(val~self)~(list~'!!))))
~~~(lazy-2~:accessor~lazy-2~:initform~(c\_?~(val~self)))
~~~(lazy-3~:accessor~lazy-3~:initform~(c?\_~(reverse~(val~self))))
~~~(val~:accessor~val~:initarg~:val~:initform~(c-in~nil))))
(defobserver~lazy-1~()
~~(format~t~\char`\"{}evaluating~lazy-1!\textasciitilde{}\%\char`\"{}))
(defobserver~lazy-2~()
~~(format~t~\char`\"{}evaluating~lazy-2!\textasciitilde{}\%\char`\"{}))
(defobserver~lazy-3~()
~~(format~t~\char`\"{}evaluating~lazy-3!\textasciitilde{}\%\char`\"{}))
(defun~print-lazies~(l)
~~(format~t~\char`\"{}Printing~all~the~values:\textasciitilde{}\%\char`\"{})
~~(format~t~\char`\"{}lazy-3:~\textasciitilde{}a\textasciitilde{}\%\char`\"{}~(lazy-3~l))
~~(format~t~\char`\"{}lazy-2:~\textasciitilde{}a\textasciitilde{}\%\char`\"{}~(lazy-2~l))
~~(format~t~\char`\"{}lazy-1:~\textasciitilde{}a\textasciitilde{}\%\char`\"{}~(lazy-1~l)))
(defun~try-lazies~()
~~(let~((l~(make-instance~'lazy-test~:val~(c-in~'(Im~very~lazy!)))))
~~~~(format~t~\char`\"{}Initialization~finished\textasciitilde{}\%\char`\"{})
~~~~(print-lazies~l)
~~~~(format~t~\char`\"{}Changing~val\textasciitilde{}\%\char`\"{})
~~~~(setf~(val~l)~'(who~will~be~evaluated?))
~~~~(print-lazies~l)))
\end{lyxcode}
As usual, load it and run it:
\begin{lyxcode}
>~(load~{}``hello-cells.lisp'')
T
>~(try-lazies)
evaluating~lazy-1!
Initialization~finished
Printing~all~the~values:
evaluating~lazy-3!
lazy-3:~(LAZY!~VERY~IM)
evaluating~lazy-2!
lazy-2:~(IM~VERY~LAZY!)
lazy-1:~(IM~VERY~LAZY!~!!)
Changing~val
evaluating~lazy-2!
Printing~all~the~values:
evaluating~lazy-3!
lazy-3:~(EVALUATED?~BE~WILL~WHO)
lazy-2:~(WHO~WILL~BE~EVALUATED?)
evaluating~lazy-1!
lazy-1:~(WHO~WILL~BE~EVALUATED?~!!)
NIL
\end{lyxcode}
As you can see from the code, to declare a ruled cell to be lazy you
just need to use the three constructs (c-formula (:lazy :one-asked)
...), (c\_? ...) and (c?\_ ...) for :once-asked, :until-asked and
:always lazy cells, respectively. lazy-1 is evaluated immediately,
lazy-2 and lazy-3 only when they are needed by format. After setting
(val l), on which all the lazy cells depend, lazy-2 is re-evaluated
immediately because it is of type :until-asked, while lazy-1 becomes
lazy and lazy-3 remains lazy, so these two postpone evaluation until
we ask for their values in the call to format.
As a side note, such short names may not be very easy to remember
and to read, but those constructs are so common that you'll find yourself
using them a lot, and you'll appreciate their conciseness. If you
still prefer long descriptive names, though, you can use the c-formula
construct instead of c?/c\_?/c?\_ and c-input instead of c-in (see
the {}``Functions \& macros reference'' section).
\section{Drifters}
Another type of cells are drifter cells. A drifter cell acts like
a ruled cell, but the value returned by its body is interpreted as
an increment, so after it has been re-evaluated its value becomes
its previous one plus the one returned by the body. The following
example shows drifter cells in action:
\begin{lyxcode}
(defmodel~counter~()
~~((how-many~:accessor~how-many
~~~~~~~~~~~~~:initform~(c...~(0)
~~~~~~~~~~~~~~~~~~~~~~~~~(length~(\textasciicircum{}current-elems))))
~~~(current-elems~:accessor~current-elems
~~~~~~~~~~~~~~~~~~:initform~(c-in~nil))))
(defun~try-counter~()
~~(let~((m~(make-instance~'counter)))
~~~~(dolist~(l~'((1~2~3)~(4~5)~(1~2~3~4)))
~~~~~~(setf~(current-elems~m)~l)
~~~~~~(format~t~\char`\"{}current~elements:~\textasciitilde{}\{\textasciitilde{}a~\textasciitilde{}\}\textasciitilde{}\%\char`\"{}~(current-elems~m))
~~~~~~(format~t~\char`\"{}\textasciitilde{}a~elements~seen~so~far\textasciitilde{}\%\char`\"{}~(how-many~m)))))
\end{lyxcode}
try-counter iterates other a list setting current-elems to a list
of values, and after each iteration how-many will hold the total number
of the elements within the lists seen so far. The output will be:
\begin{lyxcode}
>~(load~{}``hello-cells.lisp'')
T
>~(try-counter)
elements:~1~2~3
3~elements~seen~so~far
elements:~4~5
5~elements~seen~so~far
elements:~1~2~3~4~~
9~elements~seen~so~far
NIL
\end{lyxcode}
The important passage in the code is the initialization of how-many:
\begin{lyxcode}
(c...~(0)
~~(length~(\textasciicircum{}current-elems)))
\end{lyxcode}
(\textasciicircum{}current-elems) is just a shortcut for (current-elems
self). The construct (c... (<initial-value>) <body>) creates a drifter
cell whose initial value will be <initial-value>, in this case 0.
When current-elems changes, (length (\textasciicircum{}current-elems))
is re-evaluated, and its value is summed to how-many, so how-many
will hold the total number of elements that current-elems has held
so far.
\section{Cyclic dependencies}
It is possible to write code with cyclic dependencies: when A changes
you need to take some action that changes B, which in turn sets A,
but A has still to complete running the code needed to keep it in
a consistent state. The following code shows how this situation could
arise:
\begin{lyxcode}
(defmodel~cycle~()
~~((cycle-a~:accessor~cycle-a~:initform~(c-in~nil))
~~~(cycle-b~:accessor~cycle-b~:initform~(c-in~nil))))
(defobserver~cycle-a~()
~~(setf~(cycle-b~self)~new-value))
(defobserver~cycle-b~()
~~(setf~(cycle-a~self)~new-value))
(defun~try-cycle~()
~~(let~((m~(make-instance~'cycle)))
~~~~(setf~(cycle-a~m)~'(?~!))
~~~~(format~t~\char`\"{}\textasciitilde{}a~and~\textasciitilde{}a\char`\"{}~(cycle-a~m)~(cycle-b~m))))
\end{lyxcode}
When try-cycle sets cycle-a, its observer gets called, which sets
cycle-b which in turn sets cycle-a. This is not an infinite cycle
as it may seem, because the second time we set cycle-a we give it
the same value we gave it the first time, so the cells engine should
stop the propagation. Lets see if this does actually work:
\begin{lyxcode}
>~(load~{}``hello-cells.lisp'')
T
>~(try-cycle)
SETF~of~<2:A~CYCLE-B/NIL~=~NIL>~must~be~deferred~by~wrapping~code~in~WITH-INTEGRITY
~~~{[}Condition~of~type~SIMPLE-ERROR{]}
\end{lyxcode}
The message could vary depending on your Common Lisp implementation,
but one thing is clear: the code doesn't work. This happens because
when we set cycle-a for the second time, its observer is still running,
so cycle-a could be in an inconsistent state. The error message tells
us the solution: wrap the problematic code inside the with-integrity
construct, which makes sure that cycle-a is consistent when that piece
of code is run. The same problem exists for cycle-b and the solution
is the same. We need then to change
\begin{lyxcode}
(defobserver~cycle-a~()
~~(setf~(cycle-b~self)~new-value))
\end{lyxcode}
to
\begin{lyxcode}
(defobserver~cycle-a~()
~~(with-integrity~(:change)
~~~~(setf~(cycle-b~self)~new-value)))
\end{lyxcode}
and
\begin{lyxcode}
(defobserver~cycle-b~()
~~(setf~(cycle-a~self)~new-value))
\end{lyxcode}
to
\begin{lyxcode}
(defobserver~cycle-b~()
~~(with-integrity~(:change)
~~~~(setf~(cycle-a~self)~new-value)))
\end{lyxcode}
Now if we reload the code and run it we'll get the correct result.
Make sure to call (cells-reset) after an error has occurred.
\begin{lyxcode}
>~(cells-reset)
NIL
>~(load~{}``hello-cells.lisp'')
T
>~(try-cycle)
(?~!)~and~(?~!)