-
Notifications
You must be signed in to change notification settings - Fork 0
/
notes
4946 lines (4171 loc) · 161 KB
/
notes
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
Chapter 2
============================================================================
☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
============================================================================
230521 日
§2.3
13 页 apply vs. funcall
- First arg is "function designator": symbol or function object
Graham shows these as having "the same effect":
(+ 1 2)
(apply #'+ '(1 2))
(apply (symbol-function '+) '(1 2))
(apply #'(lambda (x y) (+ x y)) '(1 2))
However, they are not equivalent. Consider a different context:
[Can't rebind `+`: http://www.lispworks.com/documentation/lw50/CLHS/Body/11_abab.htm]
(defun add (&rest args)
(apply #'+ args))
(flet ((add (&rest args)
(apply #'* args)))
(add 1 2))
(flet ((add (&rest args)
(apply #'* args)))
(apply #'add '(1 2)))
(flet ((add (&rest args)
(apply #'* args)))
(apply (symbol-function 'add) '(1 2)))
(apply '+ '(1 2))
(flet ((add (&rest args)
(apply #'* args)))
(apply 'add '(1 2)))
Also
(apply #'+ '(1 2 3))
(apply #'(lambda (x y) (+ x y)) '(1 2 3))
Variations:
(apply #'+ 1 '(2 3))
(apply #'+ 1 2'(3))
(apply #'+ 1 2 3 '())
(let ((add #'+))
(apply add '(1 2 3)))
----------------------------------------------------------------------------
另见 funcall
(funcall #'+ 1 2)
(funcall (symbol-function '+) 1 2)
(funcall #'(lambda (x y) (+ x y)) 1 2)
Possible definition:
(defun funcall (f &rest args)
(apply f args))
CLHS says:
(funcall function arg1 arg2 ...) == (apply function arg1 arg2 ... nil) == (apply function (list arg1 arg2 ...))
(No need for FUNCALL in Scheme/Clojure)
(defun foo (x)
(+ x 9))
(defun bar (f x)
(funcall f x))
(bar #'foo 8) => 17
vs.
(defn foo [x]
(+ x 9))
(defn bar [f x]
(f x))
(bar foo 8) => 17
----------------------------------------------------------------------------
Side note:
(cons 'a '(b c)) => (A B C)
(list 'a 'b 'c) => (A B C)
(list* 'a 'b 'c '()) => (A B C)
CLHS:
list* is like list except that the last argument to list becomes the car of the last cons constructed, while the last argument to list* becomes the cdr of the last cons constructed. Hence, any given call to list* always produces one fewer conses than a call to list with the same number of arguments.
If the last argument to list* is a list, the effect is to construct a new list which is similar, but which has additional elements added to the front corresponding to the preceding arguments of list*.
----------------------------------------------------------------------------
Head scratchers: (Lisp I APPLY notes 279 页)
(apply #'apply #'+ 7 9 '() '())
(apply #'apply (list #'+ 7 9 '()))
(apply #'apply (list #'+ '(7 9)))
(apply #'apply '(+ (7 9)))
(apply #'apply #'+ '((7 9)))
vs.
(apply #'apply '(#'+ (7 9)))
(sdraw '(apply #'apply '(+ (7 9))))
[*|*]--->[*|*]-------------------->[*|*]--->NIL
| | |
v v v
APPLY [*|*]----->[*|*]--->NIL [*|*]--->[*|*]--->NIL
| | | |
v v v v
FUNCTION APPLY QUOTE [*|*]--->[*|*]--->NIL
| |
v v
+ [*|*]--->[*|*]--->NIL
| |
v v
7 9
(sdraw '(apply #'apply '(#'+ (7 9))) :display-width 200)
[*|*]--->[*|*]-------------------->[*|*]--->NIL
| | |
v v v
APPLY [*|*]----->[*|*]--->NIL [*|*]--->[*|*]--->NIL
| | | |
v v v v
FUNCTION APPLY QUOTE [*|*]-------------------->[*|*]--->NIL
| |
v v
[*|*]----->[*|*]--->NIL [*|*]--->[*|*]--->NIL
| | | |
v v v v
FUNCTION + 7 9
(sdraw '(#'+ (7 9)))
[*|*]-------------------->[*|*]--->NIL
| |
v v
[*|*]----->[*|*]--->NIL [*|*]--->[*|*]--->NIL
| | | |
v v v v
FUNCTION + 7 9
(sdraw (list #'+ '(7 9)))
[*|*]---------->[*|*]--->NIL
| |
v v
#<FUNCTION +> [*|*]--->[*|*]--->NIL
| |
v v
7 9
----------------------------------------------------------------------------
240414 日
(defun remove-if (f l)
(cond ((endp l) '())
((funcall f (first l)) (remove-if f (rest l)))
(t (cons (first l) (remove-if f (rest l)))) ))
(defun remove-if (f l)
(if (endp l)
'()
(destructuring-bind (first . rest) l
(if (funcall f first)
(remove-if f rest)
(cons first (remove-if f rest)))) ))
(clojure.repl/source remove)
(defn remove
"Returns a lazy sequence of the items in coll for which
(pred item) returns logical false. pred must be free of side-effects.
Returns a transducer when no collection is provided."
{:added "1.0"
:static true}
([pred] (filter (complement pred)))
([pred coll]
(filter (complement pred) coll)))
============================================================================
230613 火
§2.5
Scope
;;;
;;; Default lexical
;;;
(let ((y 7))
(defun g (x)
(list x y)))
(let ((y 5))
(g 3))
; caught STYLE-WARNING:
; The variable Y is defined but never used.
;;;
;;; Special when declared
;;;
(let ((y 7)) ; This binding is irrelevant
(declare (special y))
(defun f (x)
(declare (special y))
(list x y)))
(let ((y 5))
(declare (special y))
(f 3))
;;;
;;; More typical case
;;;
(defun f* (x)
(declare (special y))
(list x y))
(let ((y 9))
(declare (special y))
(f* 8)) ; Y indirectly "passed" to F*
;;;
;;; Persistent DECLAIM
;;;
(defvar *y* 8)
(let ((*y* 7))
(defun h (x)
(list x *y*)))
(let ((*y* 5))
(h 3))
(macroexpand-1 '(defvar *y* 8))
(PROGN (DECLAIM (SPECIAL *Y*)) (OR (BOUNDP '*Y*) (SETQ *Y* 8))
(RECORD-SOURCE-FILE '*Y* :TYPE :VARIABLE) '*Y*)
T
;;;
;;; Error
;;;
(defun p (x) (list x y))
; caught WARNING:
; undefined variable: COMMON-LISP-USER::Y
;
(let ((y 9)) (declare (special y)) (p 8))
(let ((y 9)) (p 8))
----------------------------------------------------------------------------
Notes pg. 624
(defun f (x)
(labels ((g ()
(- x 2))
(h (x)
(/ x (g))))
(+ (g) (h (* 4 x)))) )
(f 8) => 34/3
(f 1) => -5
(+ (g) (h (* 4 x)))
(+ (- x 2) (h (* 4 x)))
(+ (- x 2) (/ (* 4 x) (g)))
(+ (- x 2) (/ (* 4 x) (- x 2)))
4x
x - 2 + ------
x - 2
(defun f* (x)
(declare (special x))
(labels ((g* ()
(declare (special x))
(- x 2))
(h* (x)
(declare (special x))
(/ x (g*))))
(+ (g*) (h* (* 4 x)))) )
(f* 8) => 106/15
(f* 1) => 1
(+ (g*) (h* (* 4 x)))
(+ (- x 2) (h* (* 4 x)))
(+ (- x 2) (/ x' (g*)))
(+ (- x 2) (/ x' (- x' 2)))
x'
x - 2 + ------
x' - 2
x' = 4x
4x
x - 2 + ------
4x - 2
----------------------------------------------------------------------------
(defun make-counter (x)
#'(lambda ()
(incf x)))
(defun make-counter* (x)
(declare (special x))
#'(lambda ()
(incf x)))
(defvar *c1* (make-counter 8))
(defvar *c2* (make-counter 2))
(defvar *c3* (make-counter* 8))
(defvar *c4* (make-counter* 2))
(funcall *c1*) => 9
(funcall *c1*) => 10
(funcall *c1*) => 11
(funcall *c2*) => 3
(funcall *c2*) => 4
(funcall *c1*) => 12
(funcall *c3*)
*** - SETQ: variable X has no value
The following restarts are available:
USE-VALUE :R1 Input a value to be used instead of X.
STORE-VALUE :R2 Input a new value for X.
ABORT :R3 Abort main loop
(let ((x 8)) (declare (special x)) (print (funcall *c3*)) (print (funcall *c3*)) (print (funcall *c3*)))
9
10
11
11
(let ((x 2)) (declare (special x)) (print (funcall *c3*)) (print (funcall *c3*)) (print (funcall *c3*)))
3
4
5
5
(let ((x 2)) (declare (special x)) (print (funcall *c3*)) (print (funcall *c4*)) (print (funcall *c3*)) (print (funcall *c4*)))
3
4
5
6
6
----------------------------------------------------------------------------
Only one special variable ever exists at a given moment.
(defun foo (x)
#'(lambda () (print x)))
(defun bar (x)
(declare (special x))
#'(lambda () (print x)))
(defvar *lexical* (list (foo 2) (foo 3) (foo 4)))
(defvar *special* (list (bar 2) (bar 3) (bar 4)))
(dolist (lexical *lexical*) (funcall lexical))
(let ((x 999))
(declare (special x))
(dolist (special *special*)
(funcall special)))
(let ((x 999)
(y 4)
(z 88))
(declare (special x))
(dolist (special *special*)
(funcall special)))
----------------------------------------------------------------------------
240418 木
https://www.lispworks.com/documentation/lw50/CLHS/Body/03_abaad.htm
3.1.2.1.1.4 Symbols Naming Both Lexical and Dynamic Variables
The same symbol can name both a lexical variable and a dynamic variable, but never in the same lexical environment. ??!?!?
CLHS:
(let ((x 1)) ;Binds a special variable X
(declare (special x))
(let ((x 2)) ;Binds a lexical variable X
(+ x ;Reads a lexical variable X
(locally (declare (special x))
x))))
Me:
(defun baz ()
(let ((x 2))
(list x (symbol-value 'x)))) ; Can't call (BAZ) directly...
(defun foo ()
(let ((x 1))
(declare (special x))
(baz)))
(defun baz* ()
(let ((x 2))
(list x (boundp 'x))))
(defun foo* ()
(let ((x 1))
(declare (special x))
(baz*)))
(baz*) => (2 NIL)
(foo*) => (2 T)
----------------------------------------------------------------------------
240418 木
Fully encapsulated state
(defclass encapsulated-person ()
((state :initarg :state :reader state)))
(defmacro make-state (&rest slots)
; (let ((getters (mapcar #'(lambda (slot) (make-symbol (format nil "GET-~A" slot))) slots))
; (setters (mapcar #'(lambda (slot) (make-symbol (format nil "SET-~A" slot))) slots)))
`(let (,@(mapcar #'list slots) (g (make-hash-table))) (loop for slot in ',slots
do (setf (gethash slot g)
`#'(lambda () ,slot)))
g))
(make-instance 'encapsulated-person :state (make-state first-name last-name))
----------------------------------------------------------------------------
240415 月
(defpackage :foo
(:use :common-lisp)
(:export :foo :x)) ; <-- Creates FOO:X
(defun bar (x)
(let ((foo:x 0))
#'(lambda ()
(incf x)
(rotatef x foo:x)
(list x foo:x))))
No way Jose:
(defun bar (x)
(let ((x 0))
#'(lambda ()
(incf x)
(rotatef x x)
(list x x))))
(defvar *b1* (bar 9))
*B1*
* (defvar *b2* (bar 7))
*B2*
* (funcall *b1*)
(0 10)
* (funcall *b1*)
(10 1)
* (funcall *b1*)
(1 11)
* (funcall *b1*)
(11 2)
* (funcall *b2*)
(0 8)
* (funcall *b2*)
(8 1)
* (funcall *b2*)
(1 9)
* (funcall *b2*)
(9 2)
----------------------------------------------------------------------------
240501 水
S-expression vs. Form
* (sdraw (read))
(+ 1 2)
[*|*]--->[*|*]--->[*|*]--->NIL
| | |
v v v
+ 1 2
(+ 1 2)
(+ 1 . (2))
(cl:+ 1 2)
(common-lisp::+ 1 2)
(+ 1. 2.)
(+ 4/4 6/3)
(+ #.(/ 3 3) #.(/ 8 4))
(+ . (1 . (2 . nil)))
1
2
(+ #.** #.*)
`,(+ 1 2) ; ??? Clozure not SBCL
----------------------------------------------------------------------------
240417 水
Evaluation
The CLHS view
3.1.2.1 Form Evaluation https://www.lispworks.com/documentation/lw50/CLHS/Body/03_aba.htm
Forms fall into three categories: symbols, conses, and self-evaluating objects.
Form
/ | \
/ | \
/ | \
Symbol | Cons
|
Self-evaluating object
3.1.2.1.3 Self-Evaluating Objects
A form that is neither a symbol nor a cons is defined to be a self-evaluating object. Evaluating such an object yields the same object as a result.
Not CONS => ATOM
Not Symbol => non-symbolic atoms
Form
/ \
/ \
/ \
Atom Cons
/ \ |
Symbol Other |-Lambda Form
/ \ (Self-evaluating)|
/ \ |-Function Form
Symbol Variable |
Macro | |-Special Form
|-Constant |
| |-Macro Form
|-Lexical
|
|-Dynamic (Special)
Conses: First element (CAR) is operator.
Either:
- Symbol (names function/macro/special operator)
- Lambda expression
Function forms
(+ 2 3)
[*|*]--->[*|*]--->[*|*]--->NIL
| | |
v v v
+ 2 3
(* (+ 3 4) (- 9 1))
(* (+ 12 2) (/ 7 (- 8 3)))
Macro forms
(when (evenp 9) (cond :huh?))
-> (if (evenp 9) (cond :huh?) nil)
Special forms
(let ((x 8)) ...)
Lambda forms
((lambda (x) (* x 4)) 9)
Certain specific symbols and conses might also happen to be ``self-evaluating''
but only as a special case of a more general set of rules for the evaluation of
symbols and conses; such objects are not considered to be self-evaluating objects.
(eq #1=(quote #1#) #1#) => T ; SDRAW!!!
(eq :zed :zed) => T
(eq t t) => T
(eq t (eq nil nil)) => T
~/lisp/sbcl/sbcl-1.5.9/src/code/symbol.lisp
(setf (symbol-value t) 99)
debugger invoked on a SIMPLE-ERROR in thread
#<THREAD "main thread" RUNNING {10018301C3}>:
Veritas aeterna. (can't set SYMBOL-VALUE of T)
(setf (symbol-value nil) 99)
debugger invoked on a SIMPLE-ERROR in thread
#<THREAD "main thread" RUNNING {10018301C3}>:
Nihil ex nihil. (can't set SYMBOL-VALUE of NIL)
-------------------------------------------------
240708 月
~/lisp/books/Touretzky/2019/unary.lisp
(defconstant tally 'x)
(deftype tally () ; <------
`(member ,tally))
;; (deftype unary () ; <------ Infinite expansion!!!
;; `(or null (cons tally unary)))
(defun unaryp (n)
(every #'(lambda (elt) (typep elt 'tally)) n))
(deftype unary ()
'(satisfies unaryp))
(defun unary (n)
(loop repeat n collect tally))
----------------------------------------------------------------------------
240420 土
What does a symbol mean?
What does (+ 2 x) evaluate to? Obviously, that depends on what X means. What does
it refer to?
Suppose we have:
(let ((x "pung"))
(+ 2 x))
That looks odd since we assume that + refers to the addition operator (COMMON-LISP:+). But
the meaning of that symbol can change too:
(shadow '+)
(flet ((+ (i s)
(char s i)))
(let ((x "pung"))
(+ 2 x)))
Even more radically, 2 can become a symbol and consequently name something distinct from
its value:
(shadow '+)
(setf (symbol-function '+) #'*)
(setf *read-base* 2)
(let ((2 111)
(3 101))
(let ((x 2))
(+ x 3)))
============================================================================
240425 木
§2.6
Closures
(defun list+ (l n)
(mapcar #'(lambda (elt) (+ elt n)) l)) ; Creates closure on each invocation
; N is free variable captured from parameter
(list+ '(1 2 3 4 5) 7) => (8 9 10 11 12)
(let ((counter 0))
(defun new-id () (incf counter)) ; Creates 2 closures once
(defun reset-id () (setf counter 0))) ; <-- Controlled access to modify state
* (new-id)
1
* (new-id)
2
* (reset-id)
0
* (new-id)
1
(defun make-adder (n)
#'(lambda (x) (+ x n)))
(defvar *add2* (make-adder 2))
(defvar *add10* (make-adder 10))
(funcall *add2* 8) => 10
(funcall *add2* 9) => 11
(funcall *add10* 8) => 18
(funcall *add10* 9) => 19
(setf (symbol-function 'add20) (make-adder 20))
(add20 8) => 28
(add20 9) => 29
;;;
;;; Redefine LIST+
;;;
(defun list+ (l n)
(mapcar (make-adder n) l))
(list+ '(1 2 3 4 5) 7) => (8 9 10 11 12)
;;;
;;; Closure with semi-exposed state
;;;
(defun make-adder* (n)
#'(lambda (x &optional tweak)
(if tweak
(setf n x)
(+ x n))))
(defvar *f1* (make-adder* 1))
(funcall *f1* 2) => 3
(funcall *f1* 10) => 11
(funcall *f1* 3 t) => 3 ; Optional 2nd arg
(funcall *f1* 2) => 5
(funcall *f1* 10) => 13
============================================================================
230622 木
§2.7
(defun count-instances (obj lists)
(labels ((instances-in (list)
(if (consp list)
(+ (if (eq (first list) obj) 1 0)
(instances-in (rest list)))
0)))
(mapcar #'instances-in lists)))
(count-instances 'a '((a b c) (d a r p a) (a a)))
(1 2 2)
(count-instances 'a '((a b c) (d a r p a) (a (a) a)))
(1 2 2)
(count-instances 'a '((a b c) (d a r p a) (a a) a))
(1 2 2 0)
- Does not count top-level elements
- Does not count nested elements within each top-level list
Poor example to highlight LABELS??
(defun count-instances (obj lists)
(mapcar #'(lambda (list) (count obj list)) lists))
Not identical...
(count-instances 'a '((a b c) (d a r p a) (a a)))
(1 2 2)
(count-instances 'a '((a b c) (d a r p a) (a (a) a)))
(1 2 2)
(count-instances 'a '((a b c) (d a r p a) (a a) a))
> Error: The value A is not of the expected type SEQUENCE.
> While executing: CCL::SEQUENCE-TYPE, in process listener(1).
> Type :POP to abort, :R for a list of available restarts.
> Type :? for other options.
(defun tree-count-instances (obj tree)
(cond ((eq tree obj) 1)
((atom tree) 0)
(t (+ (tree-count-instances obj (first tree))
(tree-count-instances obj (rest tree)))) ))
(tree-count-instances 'a '((a b c) (d a r p a) (a a)))
5
(tree-count-instances 'a '((a b c) (d a r p a) (a (a) a)))
6
(tree-count-instances 'a '((a b c) (d a r p a) (a a) a))
6
见 Slade ch. 4 exercises
(defun count-occurrences (obj tree)
(cond ((null tree) 0)
((atom tree) (if (eq obj tree) 1 0))
(t (+ (count-occurrences obj (car tree))
(count-occurrences obj (cdr tree)))) ))
(deftest test-count-occurrences ()
(check
(= (count-occurrences 'a '(a ((a b)) d c (a))) 3)
(= (count-occurrences 'z '(a ((a b)) d c (a))) 0)))
Notes pg. 293
((lambda (obj lists) (labels ((instances-in (list) (if (consp list) (+ (if (eq (first list) obj) 1 0) (instances-in (rest list))) 0)))
(mapcar #'instances-in lists))) 'a '((a b c) (d a r p a) (d a r) (a a)))
=> (1 2 1 2)
(defun f (x) #'(lambda () ... x ...))
(defun g () #'(lambda (x) ... x ...))
eq?
----------------------------------------------------------------------------
240426 金
On Lisp notes 387-388 页
Anonymous recursive function
(defun recurser (f)
#'(lambda (&rest args)
(apply f f args)))
(let ((fact #'(lambda (f n)
(if (zerop n)
1
(* n (funcall f f (1- n)))) )))
(funcall (recurser fact) 8))
Direct definition:
((lambda (f) #'(lambda (n) (funcall f f n)))
#'(lambda (f n)
(if (zerop n)
1
(* n (funcall f f (1- n)))) ))
(funcall * 8) => 40320
Y Combinator!!!
(funcall ((lambda (m)
((lambda (future)
(funcall m #'(lambda (arg)
(funcall (funcall future future) arg))))
#'(lambda (future)
(funcall m #'(lambda (arg)
(funcall (funcall future future) arg)))) ))
#'(lambda (recur) #'(lambda (n) (if (zerop n) 1 (* n (funcall recur (1- n)))) )))
8)
193 页
(defmacro alambda (parms &body body)
`(labels ((self ,parms ,@body))
#'self))
(funcall (alambda (n) (if (zerop n) 1 (* n (self (1- n))))) 8) => 40320
Clojure named "anonymous" function:
((fn [x] (+ x 2)) 8) => 10
vs.
((lambda (x) (+ x 2)) 8) => 10
((fn factorial [n] (if (zero? n) 1 (* n (factorial (dec n))))) 8) => 40320
XXXXXX No can do XXXXXX
((alambda (n) (if (zerop n) 1 (* n (self (1- n))))) 8) => 40320
(defun count-instances (obj lists)
(labels ((instances-in (list)
(if (consp list)
(+ (if (eql (first list) obj) 1 0) ; Closure over OBJ
(instances-in (rest list))) ; Recursive
0)))
(mapcar #'instances-in lists)))
(defun count-instances-reduce (obj lists)
(mapcar #'(lambda (list)
(reduce #'+ (mapcar #'(lambda (elt) (if (eql elt obj) 1 0)) list)))
lists))
(defun count-instances* (obj lists)
(mapcar #'(lambda (list) (count obj list)) lists))
Using core.lisp:
(defun count-instances** (obj lists)
(mapcar (partial #'count obj) lists))
============================================================================
230704 火
§2.8 Tail Recursion (TCO)
(defun our-length (lst)
(if (null lst)
0
(1+ (our-length (cdr lst)))))
(disassemble #'our-length)
I. LABELS
(defun our-length (lst) ; <-- Not recursive!
(labels ((rec (lst acc)
(if (null lst)
acc
(rec (cdr lst) (1+ acc)))))
(rec lst 0)))
II. Optional accumulator
(defun our-length (lst &optional (acc 0))
(if (null lst)
acc
(our-length (cdr lst) (1+ acc))))
III. Separate helper function
(defun our-length (lst)
(our-length-aux lst 0))
(defun our-length-aux (lst acc)
(if (null lst)
0
(1+ (our-length-aux (cdr lst) (1+ acc)))))
- Optimize
http://www.lispworks.com/documentation/lw50/CLHS/Body/d_optimi.htm#optimize
- How to tell TCO?
- Stack overflow
(our-length (loop for i upto 10000 collect i)) => 10001
(our-length (loop for i upto 100000 collect i)) => SB-KERNEL::CONTROL-STACK-EXHAUSTED
- Disassemble
CALL -> JMP
----------------------------------------------------------------------------
FIND-IF sequence function.
- Inherently tail recursive
Oops!
(defun our-find-if (fn lst)
(if (funcall fn (car lst))
(car lst)
(our-find-if fn (cdr lst)))) ; Infinite recursion if not present!!!
(defun our-find-if (fn lst)
(cond ((endp lst) nil)
((funcall fn (car lst)) (car lst))
(t (our-find-if fn (cdr lst)))) )
(defun find-if (f list)
(if (endp list)
nil
(destructuring-bind (elt . more) list
(if (funcall f elt)
elt
(find-if f more)))) )
----------------------------------------------------------------------------
(defun triangle (n)
(labels ((tri (c n)
(declare (type fixnum n c))
(if (zerop n)
c
(tri (the fixnum (+ n c))
(the fixnum (- n 1))))))
(tri 0 n)))
1. Weird names
2. Weird order of params
3. 0..n
4. Weird algorithm
5. Weird limitation
(triangle 10000000000)
50000000005000000000
most-positive-fixnum
4611686018427387903
(log 10000000000 10)
10.0
(loop for i from 1 upto 20 collect i)
(loop for i from 20 downto 1 collect i)
(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20)
(20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1)
21 21 21
(defun sum (n)
(* n (1+ n) 1/2))
(loop for i upto n summing i)
(time (loop for i upto 1000 summing i))
; cpu time (total) 0.000003 sec user, 0.000000 sec system
(time (loop for i upto 10000 summing i))
; cpu time (total) 0.000010 sec user, 0.000000 sec system
(time (loop for i upto 100000 summing i))
; cpu time (total) 0.000085 sec user, 0.000000 sec system
(time (loop for i upto 1000000 summing i))
; cpu time (total) 0.000944 sec user, 0.000000 sec system
(time (loop for i upto 10000000 summing i))
; cpu time (total) 0.009907 sec user, 0.000000 sec system
(time (sum 1000))
; cpu time (total) 0.000010 sec user, 0.000000 sec system
(time (sum 10000))
; cpu time (total) 0.000034 sec user, 0.000000 sec system
(time (sum 100000))
; cpu time (total) 0.000014 sec user, 0.000000 sec system
(time (sum 1000000))
; cpu time (total) 0.000020 sec user, 0.000000 sec system
(time (sum 10000000))
; cpu time (total) 0.000010 sec user, 0.000000 sec system
(time (sum 100000000))
; cpu time (total) 0.000010 sec user, 0.000000 sec system
(time (sum 1000000000))
; cpu time (total) 0.000009 sec user, 0.000000 sec system
----------------------------------------------------------------------------
241002 水
Winston tail recursion examples
(Lisp 3rd Edition https://www.amazon.com/Patrick-Winston-Lisp-3rd-third/dp/B008WDDO5K/)
Reduction - In the context of tail recursion, a single derived problem whose solution
provides the answer to a given problem directly, without further computation.
The derived problem is typically simpler than the original problem.
"Whenever a problem is converted into a new problem such that no further computation is
necessary once the new problem is solved, the new problem is said to be a _reduction_ of
the original problem. Whenever a recursive procedure is defined such that all recursive calls
to itself are reductions, that procedure is said to be _tail recursive_."
(defun fact (n)
(if (zerop n)
1
(* n (fact (1- n)))) )
* (fact 6)
0: (CORE::FACT 6)
1: (CORE::FACT 5)
2: (CORE::FACT 4)
3: (CORE::FACT 3)
4: (CORE::FACT 2)
5: (CORE::FACT 1)
6: (CORE::FACT 0)
6: FACT returned 1
5: FACT returned 1 <-- Not done yet (* 1 1).
4: FACT returned 2 <-- Each step requires more computation.
3: FACT returned 6 <-- These are not the same value.
2: FACT returned 24 <-- Each step is a different problem.
1: FACT returned 120
0: FACT returned 720
720
(defun factorial (n &optional (result 1))
(if (zerop n)
result
(factorial (1- n) (* n result)))) ; This states that (factorial n result) [current call] is
; whatever is returned by (factorial (1- n) (* n result)) [recursive call]
; They are the same value. I.e.,
; (factorial (1- n) (* n result)) [new problem]
; is a reduction of (factorial n result) [original problem]
* (factorial 6)