-
Notifications
You must be signed in to change notification settings - Fork 0
/
rc-004.lisp
2212 lines (1864 loc) · 62.1 KB
/
rc-004.lisp
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
;;;; rc-004.lisp
(in-package :ros-01)
;;; Numerical and Alphabetical Suffixes
#|
This task is about expressing numbers with
an attached (abutted) suffix multiplier(s),
the suffix(es) could be:
an alphabetic (named) multiplier which
could be abbreviated
metric multiplier(s) which can be
specified multiple times
"binary" multiplier(s) which can be
specified multiple times
explanation marks (!) which indicate a
factorial or multifactorial
The (decimal) numbers can be expressed
generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±}
{digits}
where:
numbers won't have embedded blanks
(contrary to the expaciated
examples above where
whitespace was used for
readability)
this task will only be dealing with
decimal numbers, both in the
mantissa and exponent
± indicates an optional plus or minus
sign (+ or -)
digits are the decimal digits
(0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.: +7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed
to be valid and there won't be a requirement
to verify their validity.
Abbreviated alphabetic suffixes to be
supported (where the capital letters signify
the minimum abbreation that can be used)
PAIRs n x 2
SCOres n x 20
DOZens n x 12
GRoss n x 144
GREATGRoss n x 1728
GOOGOLs n x 10^100
Note that the plurals are supported, even
though they're usually used when expressing
exact numbers (She has 2 dozen eggs, and
dozens of quavas)
Metric suffixes to be supported (whether or
not they're officially sanctioned)
K n x 10^3
M n x 10^6
G n x 10^9
T n x 10^12
P n x 10^15
E n x 10^18
Z n x 10^21
Y n x 10^24
X n x 10^27
W n x 10^30
V n x 10^33
U n x 10^36
Binary suffixes to be supported (whether or
not they're officially sanctioned)
Ki n x 2^10
Mi n x 2^20
Gi n x 2^30
Ti n x 2^40
Pi n x 2^50
Ei n x 2^60
Zi n x 2^70
Yi n x 2^80
Xi n x 2^90
Wi n x 2^100
Vi n x 2^110
Ui n x 2^120
All of the metric and binary suffixes can be
expressed in lowercase, uppercase, or mixed
case.
All of the metric and binary suffixes can be
stacked (expressed multiple times),
and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T
.78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product:
5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product:
8!! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product:
8!!! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product:
8!!!! is 8 × 4 = 32
!!!!! compute the quintuple factorial
product:
8!!!!! is 8 × 3 = 24
··· the number of factorial symbols that can
be specified is to be unlimited
(as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below),
show the "expanded" numbers here, on
this page.
For each list, show the input on one
line, and also show the output on
one line.
When showing the input line, keep the
spaces (whitespace) and case
(capitalizations) as is.
For each result (list) displayed on one
line, separate each number with
two blanks.
Add commas to the output numbers were
appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has
nine factorial symbols (!) after the 9.
|#
;;; I think the best way to go about this
;;; is to use regular expressions. These
;;; are not native to CL, but there is a
;;; defacto standard 3rd-party library
;;; cl-ppcre, which I will import and use.
;;; (see rosetta.asd and packagelisp)
(defparameter *multiplicands*
(dict
:pair 2
:sco 20
:doz 12
:gr 144
:greatgr 1728
:googol #.(expt 10 100)
:k 1000
:m 1000000
:g 1000000000
:t #.(expt 10 12)
:p #.(expt 10 15)
:e #.(expt 10 18)
:z #.(expt 10 21)
:y #.(expt 10 24)
:x #.(expt 10 27)
:w #.(expt 10 30)
:v #.(expt 10 33)
:u #.(expt 10 36)
:ki #.(expt 2 10)
:mi #.(expt 2 20)
:gi #.(expt 2 30)
:ti #.(expt 2 40)
:pi #.(expt 2 50)
:ei #.(expt 2 60)
:zi #.(expt 2 70)
:yi #.(expt 2 80)
:xi #.(expt 2 90)
:wi #.(expt 2 100)
:vi #.(expt 2 110)
:ui #.(expt 2 120)))
(defparameter *keys*
'(("^(?i)pair(s)?" . :pair)
("^(?i)sco(res|re|r)?" . :sco)
("^(?i)doz(ens|en|e)?" . :doz)
("^(?i)greatgr(oss|os|o)?" . :greatgr)
("^(?i)gr(oss|os|o)?" . :gr)
("^(?i)googol(s)?" . :googol)
("^(?i)ki" . :ki)
("^(?i)mi" . :mi)
("^(?i)gi" . :gi)
("^(?i)ti" . :ti)
("^(?i)pi" . :pi)
("^(?i)ei" . :ei)
("^(?i)zi" . :zi)
("^(?i)yi" . :yi)
("^(?i)xi" . :xi)
("^(?i)wi" . :wi)
("^(?i)vi" . :vi)
("^(?i)ui" . :ui)
("^[kK]" . :k)
("^[mM]" . :m)
("^[gG]" . :g)
("^[tT]" . :t)
("^[pP]" . :p)
("^[eE]" . :e)
("^[zZ]" . :z)
("^[yY]" . :y)
("^[xX]" . :x)
("^[wW]" . :w)
("^[vV]" . :v)
("^[uU]" . :u)))
(defun multi-fac (!count)
(lambda (n)
(apply #'*
(iter
(for i from n downto 1 by !count)
(collect i)))))
(defun multi-branch (key)
(lambda (n)
(* n (gethash key *multiplicands*))))
(defun num-and-suffixes-strings (str)
(let* ((no-commas (remove #\, str))
(num
(scan-to-strings
"[+-]?\\d*\\.?\\d*([eE][-+]?\\d+)?"
no-commas)))
(let ((mismatch-index
(mismatch num no-commas)))
(if mismatch-index
(values
num
(subseq no-commas mismatch-index))
(values
num
"")))))
(defun num-string->num (num-string)
(cond
((zerop (length num-string))
0)
((every #'digit-char-p num-string)
(parse-integer num-string))
((and (= (length num-string) 1)
(digit-char-p (char num-string) 0))
(parse-integer num-string))
((and (= (length num-string) 2)
(member (char num-string 0) '(#\- #\+))
(digit-char-p (char num-string 1)))
(parse-integer num-string))
((and (= (length num-string) 2)
(digit-char-p (char num-string 0))
(char= (char num-string 1) #\.))
(parse-integer num-string :junk-allowed t))
((and (> (length num-string) 2)
(or (digit-char-p (char num-string 0))
(member
(char num-string 0)
'(#\+ #\-)))
(every #'digit-char-p
(subseq num-string 1
(- (length num-string) 1)))
(or (digit-char-p
(char num-string
(1- (length num-string))))
(char=
(char num-string
(1- (length num-string)))
#\.)))
(parse-integer num-string :junk-allowed t))
(t
(let ((*read-default-float-format*
'double-float))
(parse-float num-string)))))
(defun suffixes->fn-list (suffixes)
(if (zerop (length suffixes))
nil
(multiple-value-bind
(start end _ _)
(scan "^!+" suffixes)
(if start
(append
(suffixes->fn-list
(subseq suffixes end))
(list (multi-fac end)))
(iter
(for (regex . key) in *keys*)
(multiple-value-bind
(start end _ _)
(scan regex suffixes)
(when start
(return
(append
(suffixes->fn-list
(subseq suffixes end))
(list (multi-branch key))))))
(finally
(error
"No matching regex for ~S ~%~
suffixes->fn-list"
suffixes)))))))
(defun calculate (num fn-list)
(if (null fn-list)
(if (integerp num)
num
(float num 0d0))
(funcall (car fn-list)
(calculate num (cdr fn-list)))))
(defun parse-and-calc (str)
(multiple-value-bind
(num-str suffixes)
(num-and-suffixes-strings str)
(calculate
(num-string->num num-str)
(suffixes->fn-list suffixes))))
(defparameter *na-data*
"2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!! ")
;; Lisp has a mechanism to format integers
;; with arbitrary digit groups and
;; arbitrary separators. But no such
;; native facility exists for floats.
(defun float-commas (real)
(cond
((integerp real)
(format nil "~:D" real))
((< -1000 real 1000)
(format t "~G" real))
(t
(multiple-value-bind
(int frac)
(truncate real 1000)
(cond
((>= (abs frac) 100)
(format nil "~:D,~F" int (abs frac)))
((>= (abs frac) 10)
(format nil "~:D,0~F" int (abs frac)))
(t
(format nil "~:D,00~F" int (abs frac))))))))
(defun numeric-and-alphabetical-main ()
(let ((lines (uiop:split-string
*na-data*
:separator
'(#\Newline))))
(dolist (line lines)
(let ((expressions (tokens line)))
(format t "~%~A" line)
(format t "~%~{~A~^ ~}"
(mapcar
(lambda (ex)
(float-commas
(parse-and-calc ex)))
expressions))))))
#|
"
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
3,456 3,456 3,456 3,456 3,456.0
1,567 +1.567k 0.1567e-2m
1,567 1,567.0 1,567.0
25.123kK 25.123m 2.5123e-00002G
25,123,000.0 25,123,000.0 25,123,000.0
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
26,343,374.8480000011623 26,343,374.8480000011623 26,975,615.8443519994617 28,964,846,960.2378158569336
-.25123e-34Vikki 2e-77gooGols
-33,394.19493810443964 199,999,999,999,999,967,232,000.0
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
362,880 945 162 45 36 27 18 9 9"
Not bad. But we are dealing with floats,
so things are inaccurate.
Also. Commas? With floats? Really?
|#
;;; Amb
#|
Define and give an example of the Amb
operator.
The Amb operator (short for "ambiguous")
expresses nondeterminism. This doesn't refer
to randomness (as in "nondeterministic
universe") but is closely related to the
term as it is used in automata theory
("non-deterministic finite automaton").
The Amb operator takes a variable number of
expressions (or values if that's simpler in
the language) and yields a correct one which
will satisfy a constraint in some future
computation, thereby avoiding failure.
Problems whose solution the Amb operator
naturally expresses can be approached with
other tools, such as explicit nested
iterations over data sets, or with pattern
matching. By contrast, the Amb operator
appears integrated into the language.
Invocations of Amb are not wrapped in any
visible loops or other search patterns; they
appear to be independent.
Essentially Amb(x, y, z) splits the
computation into three possible futures: a
future in which the value x is yielded, a
future in which the value y is yielded and a
future in which the value z is yielded. The
future which leads to a successful
subsequent computation is chosen. The other
"parallel universes" somehow go away. Amb
called with no arguments fails.
For simplicity, one of the domain values
usable with Amb may denote failure, if that
is convenient. For instance, it is
convenient if a Boolean false denotes
failure, so that Amb(false) fails, and thus
constraints can be expressed using Boolean
expressions like Amb(x * y == 8) which
unless x and y add to four.
A pseudo-code program which satisfies this
constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3)
correctly chooses the future in which x has
value 2, Amb(7, 6, 4, 5) chooses 4 and
consequently Amb(x * y = 8) produces a
success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the
Boolean expression is false, otherwise it
allows the future computation to take place,
without yielding any value.
The task is to somehow implement Amb, and
demonstrate it with a program which chooses
one word from each of the following four
sets of character strings to generate a
four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the
last character of each word (other than the
last) is the same as the first character of
its successor.
The only successful sentence is "that thing
grows slowly"; other combinations do not
satisfy the constraint and thus fail.
The goal of this task isn't to simply
process the four lists of words with
explicit, deterministic program flow such
as nested iteration, to trivially
demonstrate the correct output. The goal is
to implement the Amb operator, or a
facsimile thereof that is possible within
the language limitations. |#
;; This implementation is taken from
;; Paul Graham's On Lisp. It uses macros
;; to simulate Scheme continuations, which
;; are employed to make the amb operator.
;; First, we need a global LEXICALLY scoped
;; parameter that will reference a
;; continuation.
(setq *cont* #'identity)
;; Next, the basic machinery for amb
(defparameter *paths* nil
"Used to store paths of future computation
that have not yet been tried.")
(defconstant +failsym+ '@
"Symbol to indicate failure. We decided
to use a dedicated symbol for amb failure,
since NIL already has 3 meanings: the
empty list, Boolean false and search
failure.")
(defun fail ()
"When a choice fails, we try the next choice.
If there is no next choice, we return
+failsym+"
(if *paths*
(funcall (pop *paths*))
+failsym+))
(defmacro amb (&rest choices)
(if choices
`(progn
,@(mapcar
#'(lambda (c)
`(push
#'(lambda () ,c)
*paths*))
(reverse (cdr choices)))
,(car choices))
'(fail)))
(defun cb (fn choices)
"Auxiliary function for amb-bind."
(if choices
(progn
(when (cdr choices)
(push
#'(lambda () (cb fn (cdr choices)))
*paths*))
(funcall fn (car choices)))
(fail)))
(defmacro amb-bind (var choices &body body)
"Convenience macro to facilitate supplying
amb with choices that are functions. Not
strictly necessary"
`(cb #'(lambda (,var) ,@body) ,choices))
;; Now we need a continuations mechanism.
;; This allows us to actually use amb.
;; A continuation stores the environment
;; of a specific code stack frame, allowing
;; us to use it at a moment's notice.
;; The lexical global parameter *cont*,
;; above, is necessary for the code that
;; follows.
;; The majority of the following
;; macros simulate native CL operators,
;; but they make sure information about
;; the stack frame is always stored.
;; The CL operators have the same names
;; as these, without the initial =.
(defmacro =lambda (parms &body body)
"Creates a local, anonymous function."
`#'(lambda (*cont* ,@parms) ,@body))
(defmacro =defun (name parms &body body)
"Define a new dynamic/global function.
Unlike defun, =defun requires a
special operator in functions to
return values. This is =values, below."
(let ((f (intern (concatenate 'string
"="
(symbol-name
name)))))
`(progn
(defmacro ,name ,parms
`(,',f *cont* ,,@parms))
(defun ,f (*cont* ,@parms) ,@body))))
(defmacro =bind (parms expr &body body)
"The cl macro is multiple-value-bind.
Receives multiple values from a single
expr, binds them to parms, and executes
body in the lexical environment of the
bindings."
`(let ((*cont* #'(lambda ,parms ,@body)))
,expr))
(defmacro =values (&rest retvals)
"Like 'values' in that it can be used
to return multiple values from a function.
In addition, all functions written with
=defun that return one or more values
must either end with =values or with
a call to a function that does."
`(funcall *cont* ,@retvals))
(defmacro =funcall (fn &rest args)
"Call a function passed as an argument."
`(funcall ,fn *cont* ,@args))
(defmacro =apply (fn &rest args)
"Call a function, using the elements of
a list as its arguments."
`(apply ,fn *cont* ,@args))
;; Finally, the required task
(=defun words ()
(amb-bind word1 '("the" "that" "a")
(amb-bind word2 '("frog" "elephant" "thing")
(amb-bind word3 '("walked" "treaded" "grows")
(amb-bind word4 '("slowly" "quickly")
(=values word1 word2 word3 word4))))))
(=defun amb-main ()
(=bind (w1 w2 w3 w4) (words)
(if
(and
(char= (char w1 (1- (length w1)))
(char w2 0))
(char= (char w2 (1- (length w2)))
(char w3 0))
(char= (char w3 (1- (length w3)))
(char w4 0)))
(list w1 w2 w3 w4)
(fail))))
;; ("that" "thing" "grows" slowly")
;;; History Variables
#|
Storing the history of objects in a program
is a common task. Maintaining the history of
an object in a program has traditionally
required programmers either to write
specific code for handling the historical
data, or to use a library which supports
history logging.
History variables are variables in a
programming language which store not only
their current value, but also the values
they have contained in the past. Some
existing languages do provide support for
history variables. However these languages
typically have many limits and restrictions
on use of history variables.
[http://www.bod.com/index.php?id=3435&objk_id=148050
"History Variables: The Semantics, Formal
Correctness, and Implementation of History
Variables in an Imperative Programming
Language" by Mallon and Takaoka]
Concept also discussed on LtU and
Patents.com.
Task
Demonstrate History variable support:
enable history variable support
(if needed)
define a history variable
assign three values
non-destructively display the history
recall the three values.
For extra points, if the language of choice
does not support history variables,
demonstrate how this might be implemented.
|#
;; History variables are not a part of the
;; CL standard. They can be implemented
;; rather easily using macros and
;; property lists.
;; Arbitrary combinations of letters,
;; numbers and other glyphs, which would
;; be recognized as variables in most
;; languages are called symbols in the list
;; family. They are most frequently used
;; as variables, but can also be used as
;; objects in their own right, and take
;; the place of strings in some applications.
;; Every symbol contains a property list,
;; a very simple associative list, which
;; contains certain default properties, and
;; to which arbitrary additions can be made.
;; We can store a list of prior values
;; keyed to some keyword, like :history.
;; A macro must be used to manipulate a
;; symbol for binding, so we need that
;; facility.
(defmacro add-history (var)
"Aux macro for set-hist"
`(push
,var
(get ',var :history nil)))
(defmacro set-history-var (var expr)
"Setter for a history variable"
(let ((gexpr (gensym "gexpr")))
`(let ((,gexpr ,expr))
(setf ,var ,gexpr)
(add-history ,var)
,gexpr)))
(defun get-history (quoted-var)
"Returns the history of a history variable."
(if
(not
(member
:history
(symbol-plist quoted-var)))
(format t "~A is not a history variable."
quoted-var)
(get quoted-var :history)))
(defmacro recall (var)
(let ((value (gensym "value")))
`(cond
((not (member
:history
(symbol-plist ',var)))
(error
"~A not a history variable."
',var))
((null (get ',var :history))
(setf ,var nil))
(t
(pop (get ',var :history))
(setf ,var (car (get ',var :history)))))))
#|
(set-history-var h 25)
-> 25
h
-> 25
(set-history-var h 50)
-> 50
h
-> 50
(set-history-var h 75)
-> 75
h
-> 75
(get-history 'h)
-> (75 50 25)
h
-> 75
(recall h)
-> 50
h
-> 50
(recall h)
-> 25
h
-> 25
(recall h)
-> NIL
h
-> NIL
(recall h)
-> NIL
h
-> NIL
(get-history 'sam)
printout-> SAM not a history variable
-> NIL
(revert sam)
error-> SAM not a history variable
|#
;;; Parsing/Shunting-yard Algorithm
#|
Given the operator characteristics and input
from the Shunting-yard algorithm page and
tables, use the algorithm to show the
changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space
separated, string of tokens representing
an infix expression
Generate a space separated output string
representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this
table:
operator precedence associativity operation
^ 4 right exponentiation
* 3 left multiplication
/ 3 left division
+ 2 left addition
- 2 left subtraction
Extra credit
Add extra text explaining the actions and an
optional comment for the action on receipt
of each token.
Note
The handling of functions and arguments is
not required. |#
(defparameter *precedence*
'(("^" . 4)
("*" . 3)
("/" . 3)
("+" . 2)
("-" . 2)))
(defun precedence> (op1 op2)
(> (cdr (assoc op1 *precedence* :test #'equal))
(cdr (assoc op2 *precedence* :test #'equal))))
(defun operatorp (token)
(member token '("^" "*" "/" "+" "-")
:test #'equal))
(defun infix-list->rpn-list (infix-list)
(let ((res-stack nil)
(op-stack nil))
(dolist (token infix-list
(progn
(dolist (op op-stack)
(push op res-stack))
(nreverse res-stack)))
(cond
((equal token "(")
(push token op-stack))
((equal token ")")
(iter
(for prev = (pop op-stack))
(until (equal prev "("))
(push prev res-stack)))
((operatorp token)
(if (null op-stack)
(push token op-stack)
(let ((prev (car op-stack)))
(cond
((equal prev "(")
(push token op-stack))
((equal token "^")
(push token op-stack))
((precedence> token prev)
(push token op-stack))
(t
(iter
(for prev = (car op-stack))
(while op-stack)
(while
(not
(equal prev "(")))
(while
(not
(precedence> token prev)))
(push
(pop op-stack)
res-stack)
(finally
(push token op-stack))))))))
(t
(push token res-stack))))))
(defun tokenize (str)
(uiop:split-string str :separator " "))
(defparameter *shunting-data*
"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3")
(defun shunting-main ()
(let ((infix-list (tokenize *shunting-data*)))
(format t "~%~{~A~^ ~}"
(infix-list->rpn-list infix-list))))
;; 3 4 2 * 1 5 - 2 3 ^ ^ / +
;;; Graph Colouring
#|
A Graph is a collection of nodes (or
vertices), connected by edges (or not).
Nodes directly connected by edges are called
neighbours.
In our representation of graphs, nodes are
numbered and edges are represented by the
two node numbers connected by the edge
separated by a dash. Edges define the nodes
being connected. Only unconnected nodes need
a separate description.
Example graph
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
A useful internal datastructure for a graph
and for later graph algorithms is as a
mapping between each node and the set/list
of its neighbours.
In the above example:
0 maps-to 1 and 2
1 maps to 2 and 0
2 maps-to 1 and 0
3 maps-to <nothing>