-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwamcompiler.tex
5405 lines (4761 loc) · 170 KB
/
wamcompiler.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
\documentclass[a4paper,12pt]{book}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{menukeys}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage[T1]{fontenc}
\usepackage{upquote}
\usepackage{wrapfig}
\usepackage{makeidx}
\usepackage{tikz, pgf}
\usepackage{listing}
\usepackage{fancyvrb}
\usetikzlibrary{backgrounds, positioning, %% Draw Y-chart
snakes, fit, %% Draw Y-chart
3d, arrows, automata, shapes.gates.logic.US,
shapes.gates.logic.IEC, calc,
circuits.logic.US}
\usepackage{circuitikz}
\newsavebox{\fmbox}
\newenvironment{fmpage}[1]
{\begin{lrbox}{\fmbox}\begin{minipage}{#1}}
{\end{minipage}\end{lrbox}\fbox{\usebox{\fmbox}}}
\addto\captionsenglish{\renewcommand{\figurename}{Listing}}
\makeindex
\title{An introduction to Prolog and wamcompiler\\
{\normalsize (Content not (yet) checked for grammar and spelling errors)}}
\author{Vernon Sipple \and ed500ac \and Marcus \and Lucas}
\date{}
\begin{document}
\maketitle
\thispagestyle{empty}
\mainmatter
\chapter{Emacs commands}
Emacs is the text editor that Lisp programmers prefer.
To give you a head start, this chapter lists the basic
commands you need to edit a file.
In the following cheat sheet, \verb|Spc| denotes
the space bar, \verb|C-| is the \keys{Ctrl} prefix, \verb|M-| represents
the \keys{Alt} prefix and $\kappa$ can be any key.
\paragraph{Basic commands.} \verb|C-|$\kappa$ -- Press and release \keys{Ctrl}
and \keys{$\kappa$} simultaneously
\begin{quote}
\verb|C-s| then type some text, and press \verb|C-s| again
-- search a text.\\
\verb|C-r| then type some text, and press \verb|C-r| again
-- reverse search.\\
\verb|C-k| -- kill a line.\\
\verb|C-h| -- backspace.\\
\verb|C-d| -- delete char forward.\\
\verb|C-Spc| then move the cursor -- select a region.\\
\verb|M-w| -- save selected region into the kill ring. \\
\verb|C-w| -- kill region.\\
\verb|C-y| -- insert killed or saved region.\\
\verb|C-g| -- cancel minibuffer reading.\\
\verb|C-a| -- go to beginning of line.\\
\verb|C-e| -- go to end of line.\\
\verb|C-b| -- move backward one character.\\
\verb|C-f| -- move forward one character.\\
\verb|C-n| -- move cursor to the next line.\\
\verb|C-p| -- move cursor to the previous line.\\
\verb|C-l| -- refresh screen.\\
\verb|C-u| -- undo. \\
\verb|C-v| -- forward page.\\
\keys{INS} -- toggle overwrite mode.\\
\keys{$\leftarrow$} \keys{$\rightarrow$} \keys{$\uparrow$} \keys{$\downarrow$} -- arrows move cursor.\\
\end{quote}
\paragraph{Control-x commands.} \verb|C-x C-|$\kappa$ -- Keep \keys{Ctrl}
down and press \keys{x} and \keys{$\kappa$}
\begin{quote}
\verb|C-x C-f| -- open a file into a new buffer.\\
\verb|C-x C-w| -- write file with new name.\\
\verb|C-x C-s| -- save file.\\
\verb|C-x C-c| -- exit Emacs.\\
\verb|C-x i| -- insert file at the cursor.\\
\verb|C-h b| -- lists all key strokes.\\
\end{quote}
\paragraph{Window commands.} One can have more
than one window on the screen. Below, you will
find commands that deal with this situation.
\begin{itemize}
\item \verb|C-x |$\kappa$ -- Press and release \keys{Ctrl}
and \keys{x} together, then press \keys{$\kappa$}
\begin{quote}
\verb|C-x b| -- next buffer.\\
\verb|C-x C-b| -- list buffers.\\
\verb|C-x k| -- kill current buffer.\\
\verb|C-x =| -- code for char under the cursor.\\
\verb|C-x 2| -- split window into cursor window and other window.\\
\verb|C-x o| -- jump to the other window.\\
\verb|C-x 1| -- close the other window.\\
\verb|C-x 0| -- close the cursor window.
\end{quote}
\item \verb|Esc| $\kappa$ -- Press and release the \keys{Esc} key,
then press the \keys{$\kappa$} key.
\begin{quote}
\verb|Esc >| -- go to the end of buffer.\\
\verb|Esc <| -- go to the beginning of buffer.\\
\verb|Esc f| -- word forward.\\
\verb|Esc b| -- word backward.\\
\end{quote}
\item \verb|M|-$\kappa$ -- Keep the \keys{Alt} key
down and press the \keys{$\kappa$} key.
\begin{quote}
\verb|M-b| -- move backward one word.\\
\verb|M-f| -- move forward one word.\\
\verb|M-g| -- go to the line given in the minibuffer.\\
\verb|M-n| -- activate the next buffer.\\
\verb|M-r| -- query replace.
\end{quote}
\end{itemize}
\paragraph{Query replace.} If you press \keys{Esc}\keys{\%},
the computer enters into the query replace mode.
First, Emacs prompts for the text snippet S
that you want to replace. Then it prompts for
the replacement R. When you type the R text and
press the \keys{Enter} key, the cursor jumps to
the first occurence of S, and Emacs asks whether
you want to replace it. If the answer is \verb|y|,
Emacs will replace S with \verb|R| and jump to
the next occurence. If the answer is \verb|n|,
Emacs will jump to the next occurrence of S without
performing the replacement.
\paragraph{Go to line.} When you try to compile
code containing errors, the compiler
usually reports the line number where the error occurred.
If you press \verb|C-u 3| \keys{Esc}\keys{g}\keys{Esc}\keys{g},
the cursor jumps to the line where the error occurred,
for instance, to line 3.
In order to know the position of the cursor, press
the \verb|C-x =| command, and Emacs gives information
concerning the character under the cursor, the corresponding
code, the line, and the character position in the text.
\paragraph{List bindings.} If you press
the \verb|C-h b| command, the computer
lists all Emacs commands. Then you
can check whether I forgot one or other keybinding in this
tutorial. In order to issue this command, keep
the \keys{Ctrl} key down and press \keys{x}, then release
both keys and press the \keys{?} key.
\paragraph{Nia Vardalos.}
In order to get acquainted with editing and scripting,
let us accompany the Canadian programmer Nia Vardalos,
while she explores Emacs. Disclaimer: Nia, the coder,
is not related to Nia, the actress.
When text is needed for carrying out a command,
it is read from the minibuffer, a one line
window at the bottom of the screen. For instance,
if Nia presses \verb|C-s| for finding a text,
the text is read from the minibuffer, and while Nia is
still typing, Emacs starts the search. When she finds
what she is looking for, Nia strikes the \keys{Enter}
key to stop the interactive search. Nia can press
\verb|C-s| again to find other instances of the text.
To transport a region from one place to another,
Nia presses \verb|C-Spc| to start
the selection process and move the cursor to select
a region. Then she presses \verb|C-w| to kill her
selection. Finally, she moves the cursor to the
insertion place, and presses the \verb|C-y| shortcut.
To copy a region, Nia presses \verb|C-Spc| and moves
the cursor to select the region. Then she presses
\verb|M-w| to save the selection into the kill ring. Finally,
she takes the cursor to the destination, where the copy is to
be inserted and issues the \verb|C-y| command.
Nia noticed that there are two equivalent ways to
issue an \verb|M-|$\kappa$ command. She can
press and release the \keys{Esc} key, then
strike the $\kappa$ key. Alternatively, she
can keep the \keys{Alt} key down and press
the \keys{$\kappa$} key.
\paragraph{Calculations with Lisp.} Emacs
offers a Lisp dialect to perform calculations
and text processing. Let us assume that you
want to find out how many students graduate from
medical schools in California. You type the Lisp
addition command, then press \verb|C-x C-e| with
the cursor in front of it:
\begin{quote}
\verb|> (+ 190 180 170 160 120 100 100 90)|\keys{C-x C-e}
\end{quote}
In the above expression, the first thing that follows
the open parenthesis is the \verb|+| sum
operation identifier. After the name of
the operation, there is a list of
the arguments to be added together.
Emacs shows the result of the addition as soon as
Nia presses the \keys{C-x C-e} command:
\begin{quote}
\verb|1110|
\end{quote}
The rule that worked for the $\verb|(+ | x_1\;x_2\ldots\verb|)|$
sum operation also works for the other arithmetic function too.
\begin{itemize}
\item{Multiplication} is performed
by the \verb|*| operation.
\begin{quote}
\verb|> (* 1 2 3 4 5)|\keys{C-x C-e}\\
120
\end{quote}
\item{Division} is obtained through the \verb|/| operation.
\begin{quote}
\verb|> (* 1 2 4)|\keys{C-x C-e}\\
0.125
\end{quote}
The above operation performed the chain
division \verb|1/2/3|.
\item{Subtraction} has the syntax shown below.
\begin{quote}
\verb|> (- 1 2 4)|\keys{C-x C-e}\\
-5
\end{quote}
\item Mixed operations. One can nest subexpressions
within an outer expression. For instance,
to get the average student number graduating
from medical school in California, one can
calculate the expression:
\begin{quote}
\verb|> (/ (+ 190 180 170 160 120 100 100 90) 8)|\keys{C-x C-e}
\end{quote}
\end{itemize}
\paragraph{Command execution.} When you press
shortcut keys, Emacs calls a command written in
C or in Lisp. You can get a complete list of all
Emacs commands by pressing the \verb|C-x ?| shortcut.
There are commands that are not associated to
shortcut keys. For instance, the \verb|lisp-mode|
function tells Emacs that you are editing Lisp code.
In order to issue such a command, keep the \keys{Alt}
key down and press the \keys{~x~} key. The \verb|M-x|
prompt will be placed on the minibuffer. Type
\verb|lisp-mode| in front of the prompt:
\begin{quote}
\verb|M-x lisp-mode|
\end{quote}
When typing a command at the \verb|M-x| prompt, you
often don't remember the complete name of the operation.
In this case, type press the \keys{Tab} key, and Lisp will
list the options available to complete the name.
\begin{verbatim}
backspace backspace
C-a move-beginning-of-line
C-b backward-char
C-d delete-char
C-e move-end-of-line
C-f forward-char
C-h help-command
C-k kill-line
C-l recenter-top-bottom
C-n next-line
C-p previous-line
C-r isearch-backward
C-space set-mark
C-s isearch-forward
C-/ undo
C-v scroll-up-command
C-w kill-region
C-x 1 delete-other-windows
C-x 2 split-window-below
C-x C-b list-buffers
C-x C-c save-buffers-kill-terminal
C-x C-f find-file
C-x C-s save-buffer
C-x = cursor-position
C-x C-w write-file
C-x i insert-file
C-x k kill-buffer
C-x o other-window
C-y yank
down next-line
esc a apropos
esc B backward-word
esc b backward-word
esc < beginning-of-buffer
esc d kill-line
esc > end-of-buffer
esc esc show-version
esc F forward-word
esc f forward-word
esc G goto-line
esc g goto-line
esc i yank
esc k kill-region
esc l list-bindings
esc m set-mark
esc n next-buffer
esc o delete-other-windows
right forward-character
up previous-line
\end{verbatim}
\chapter{Installation}
In order to program in Prolog, you will need
to install three programs:\index{wamcompiler}
\begin{enumerate}
\item Emacs -- a text editor\index{wamcompiler!Emacs}
\item Steel Bank Common Lisp, or sbcl for
short\index{wamcompiler!sbcl}
\item A Prolog compiler that works in tandem with Lisp,
such as \verb|cl-prolog| that links Lisp with a
popular implementation of Prolog, or
a Lisp based Prolog, such as the \verb|wamcompiler.lisp|
virtual machine.
\end{enumerate}
However, you must learn many things before actually being
able to make these three pieces of software work together.
Unless you are well versed in programming, I suggest that
you call a geek who has majored in Computer Science to perform
the installations for you.
Installation of Emacs is quite easy. You will find binary
distributions for practically any machine. Even so, you
will need help to configure the editor and perform the
setup of useful plug-ins, such as slime, which will help
you with Lisp programming.
Installation of sbcl is slightly more difficult. The
best approach is to install roswell, which is a Lisp
implementation installer/manager and launcher. Search
the Internet for the roswell page and follow the
instructions with the help of the Computer Science major.
Use the keywords {\em Common Lisp roswell} to find
the github repository for roswell.
Finally you will need to download the \verb|wamcompiler.lisp|
file. The \verb|wamcompiler| was developed by Daiki Matsunaga,
who publish under the nickname of \verb|matsud224|. Therefore,
a search with the following keywords should land on the
wamcompiler page: \verb|matsud224 wamcompiler|.
\index{wamcompiler!github}
Besides Prolog, this book will deal with Common
Lisp and shell script, thus if you go through the whole
text, you will not need help from the Computer Science
major pretty soon.
\section{Ready}
If you installed Emacs and sbcl, then performed the download
of the wamcompiler, you are now ready for action!
\includegraphics{figs-prefix/readyforaction.jpg}
It seems that people prefer money to sex.
After all, almost everybody says no to
sex on one occasion or another.
But I have never seen a single
person refusing money. Therefore, let us
start this tutorial talking about money.
If one wants to calculate a running
total of bank deposits, she will make
a column of numbers and perform the
addition.
\index{Arithmetic!Elemetary School}
\begin{wrapfigure}[10]{i}{5cm}
\renewcommand\figurename{Fig.}
\includegraphics[scale=0.5]{figs-prefix/firemen.png}
\caption{Running total}
\end{wrapfigure}
What I mean to say is that, if you
need to perform the addition
$8 + 26 + 85 + 3$ with pencil and paper,
you will probably stack the numbers the
same way you did before taking pre-algebra
classes in highschool:
\begin{quote}
\begin{tabular}{p{0.5cm}p{1cm}}
+ &\verb| 8|\\
&\verb| 26|\\
&\verb| 85|\\
&\verb| 3|\\
\hline
&\verb|122|
\end{tabular}
\end{quote}
Subtraction is not treated differently:
\begin{quote}
\begin{tabular}{p{0.5cm}p{1.5cm}}
\Large\bf -& 358\\
& 216\\
\hline
& 142
\end{tabular}
\end{quote}
This chapter contains an introduction to
the Cambridge prefix notation,
which is only slightly different from that
learned in elementary school: The operation
and its arguments are put between parentheses.
In doing so, one does not need to draw a line
under the bottom number, as you can see below:
\begin{quote}
\begin{tabular}{p{0.5cm}p{1cm}}
(+ &\verb| 8|\\
&\verb| 26|\\
&\verb| 85|\\
&\verb| 3|)\\
&\verb|122|
\end{tabular}
\end{quote}
The Cambridge prefix notation can be applied
to any operation, not only to the four arithmetic
functions.
\section{Cambridge prefix notation}
\index{Prefix notation}
\index{Prefix notation!Cambridge}
Let us summarize what we have learned
until now. In pre-algebra, students
learn to place arithmetic operators (+, -, × and ÷)
between their operands; e.g. 347+45.
However, when doing additions and subtractions
on paper, they stack the operands.
\includegraphics{figs-prefix/stackshark.jpg}
Lisp programmers put operation and operands
between parentheses. The right parenthesis
separate the operands from the result,
instead of drawing a line under the last operand.
\includegraphics{figs-prefix/neatsum.jpg}
\section{Pictures}
Here is the story of a Texan who went on
vacation to a beach in Mexico. While he was
freely dallying with the local beauties,
unbeknowest to him a blackmailer took some
rather incriminating photos.
After a week long gallivanting, the Texan
returns to his ranch in a small town near Austin.
Arriving at his door shortly after is the blackmailer
full of bad intentions.
Unaware of any malice, the Texan allows the so
called photographer to enter and sit in front
of his desk. Without delay, the blackmailer spread
out a number of photos on the desk, along with his
demands: “For the photo in front of the hotel,
that will cost you \$~25320.00. Well, the one
on the beach that's got to be \$~56750.00.
Finally, this definitively I can't let
go for less than \$~136000.00.”
Once finished with his presentation,
the blackmailer snaps up the photos,
and looks to the Texan with a sinister
grin, awaiting his reply.
Delighted with the selection of pics,
the Texan in an elated voice says:
“I thought I would have no recollection
of my wonderful time. I want 3 copies
of the hotel shot, half a dozen of the beach.
And the last one, I need two copies for myself,
and please, send one to my ex-wife.
Make sure you leave me your contact
details; I might need some more.
\paragraph{Mixed calculations.}
In order to calculate how much the
Texan must pay his supposed blackmailer,
his bookkeeper needs to perform the
following operations:
$$3\times 25320+6\times 56750 + 2\times 136000+136000$$
It should be remembered that multiplications
within an expression take priority over additions
and subtractions. The bookkeeper must therefore
calculate the first two products $3\times 25320$
and $6\times 56750$, before performing the first
addition. In the Cambridge prefix notation,
the internal parentheses pass priority over
to the multiplications.
The Texan's bookkeeper started Emacs
in order to perform the calculations.
The text editor creates a memory
buffer that mirrors the file contents.
By convention, the file and the buffer
have the same name.
Initially, Emacs will place the bookkeeper
on a *scratch* buffer. The bookkeeper issues
the \verb|M-x| command by keeping the \keys{Alt}
key down and pressing the \verb|x| key.
Emacs will put the bookkeeper in the minibuffer
with the \verb|M-x| prompt. Then, the bookkeeper
will type the \verb|shell| command, which we
will study in one of the future chapters.
Here is how to start the shell:
\begin{quote}
\verb|M-x shell| \keys{Enter}
\end{quote}
The above command will create a kind of chat
box between the bookkeeper and the computer.
The bookkeeper types the \verb|ros run| command
to start Lisp. Listing~\ref{texan:photos} shows
what an interaction with shell and sbcl looks
like. After typing an expression, while obeying the
Cambridge prefix notation syntax,
the bookkeeper moves the cursor to the front
of the most external right parenthesis.
To perform the calculation, she presses
the \keys{Enter} key. Then, the sbcl Read Eval
Print Loop transforms the command to machine
language, evaluates it, and inserts the result into
the buffer.
To save the buffer, the bookkeeper
keeps the \keys{Ctrl} key down, and presses
the \keys{~x~} and \keys{~s~} keys in sequence.
To exit the editor, she maintains the \keys{Ctrl}
key pressed and hits the \keys{~x~} and \keys{~c~}
keys one after the other. If there are unsaved files,
the editor warns that modified buffers exist,
and requires confirmation before quitting. But wait,
if you are shadowing the actions of the bookkeeper,
don't leave the editor yet. Let us test the wamcompiler
before doing so.
\begin{figure}[!h]
\begin{fmpage}{0.8\textwidth}
\verb|~/wamcompiler/wamdocs master ×|\\
\verb|› ros run|\\
\verb|* (+ (* 3 25320)|\\
\verb| (* 6 56750)|\\
\verb| (* 2 136000)|\\
\verb| 136000 )|\keys{Enter}\\
824460
\end{fmpage}
\begin{fmpage}{0.8\textwidth}
\verb| |
\end{fmpage}
\caption{Chat with Lisp}
\label{texan:photos}
\end{figure}
The Texan's accountant decided to check whether
the wamcompiler is working on her machine. Therefore,
she loads the \verb|wamcompiler.lisp| file and
starts a Prolog Read Eval Print Loop, or repl for
short.
\begin{quote}
\begin{verbatim}
* (load "~/wamcompiler/wamcompiler.lisp")
(load "~/wamcompiler/wamcompiler.lisp")
T
* (repl)
(repl)
> ?- X is 3*25320 + 6*56750+ 2* 136000 + 136000.
?- X is 3*25320 + 6*56750+ 2* 136000 + 136000.
X = 824460
yes.
> ?- halt.
yes.
\end{verbatim}
\end{quote}
The Lisp prompt is usually an asterisk, therefore
be careful not to confuse the prompt with the
multiplication symbol. The wamcompiler prompt is
the {\em greater-than} \verb|>| character, but you need to prefix
all queries with the \verb|?-| symbol, as you
can see in the example.
\section{Time value of money}
Suppose that you wanted to buy a \$ 100,000 red Ferrari,
and the forecourt salesperson in his eagerness to
close a deal gives you the following two payment options:
\begin{itemize}
\item Pay \$ 100,000 now {\bf or}
\item pay the full \$ 100,000 after a three year grace period.
\end{itemize}
I am sure that you would choose to pay the \$ 100,000 after
three years of grace has finished, although you have the
money in a savings account waiting for a business
opportunity. But why is this? After all, you will need
to pay the debt one way or the other. However, if you
keep the money in your power during the grace period,
you can earn a few months of fuel from the interest.
You may not know for sure how much interest you
will earn in three years, but since the salesperson
is not charging you for deferring the payment,
whatever you gain is yours to keep.
Unfortunately for you, the above scenario would
more than probably not happen in real life.
The right to delay payment until some future
date is a merchandise with a price tag,
which {\em is called interest by those who
think it lawful, and usury by those who
do not} (William Blackstone's Commentaries
on the Laws of England). Therefore, unless
the salesperson is your favorite aunt,
the actual offer is like jumping into a tank
full of sharks as in the classic James Bond films.
It requires a little forethought and understanding
of how interest works, before making a decision.
Here is a more realistic real estate sales offer:
\begin{itemize}
\item \$ 100,000 now {\bf or}
\item \$ 115,000 at the end of three years.
\end{itemize}
What to do when facing an increase in price
to cover postponement of payment? The best
policy is to ask your banker how much interest
she is willing to pay you over your
granted grace period.
Since the economy performance is far
from spectacular, your banker offers you
an interest rate of 2.5\%, compound annually.
She explains that compound interest arises
when interest is paid on both the principal
and also on any interest from past years.
\section{Future value}\index{Future Value}
\includegraphics{figs-prefix/piggy.jpg}
The value of money changes with time. Therefore,
the longer you keep control of your money,
the higher its value becomes, as it can earn
interest. Time Value of Money, or TVM for short,
is a concept that conveys the idea that money
available now is worth more than the same
amount in the future.
If you have \$ 100,000.00 in a savings account
now, that amount is called {\em present value},
since it is what your investment would give you,
if you were to spend it today.
Future value of an investment is the amount
you have today plus the interest that your
investment will bring at the end of a
specified period.
The relationship between the present value
and the future value is given by the
following expression:
\begin{equation}
FV= PV\times (1+i)^n
\label{eq:future-value}
\end{equation}
where $FV$ is the future value, $PV$ is the present
value, $i$ is the interest rate divided by 100,
and $n$ is the number of periods.
In the case of postponing the payment of a \$ 100,000.00 car
for 3 years, at an interest rate of 0.025, the future
value of the money would be 107,689.06; therefore,
I strongly recommend against postponing the payment.
\section{Compound interest}
Our Texan decides he needs a break. Thus he walks into
a New York City bank and asks for the loan officer.
He tells a story of how through his doctor's recommendation
he was taking it easy at his property in the south of
France for two whole years and for such an
emergency he needs a \$ 10,000.00 loan.
The loan officer said that the interest was a compound 8\%
a year, but the bank would need some collateral for the loan.
“Well, I have a 60 year old car that I like very much.
Of course, I cannot take it with me to France.
Would you accept it as collateral?”
Unsure whether or not the old car was worth the
amount of the loan, the officer summons the bank manager.
The manager inspects the vehicle that was parked on the
street in front of the bank. After a close examination,
he gives a nod of approval: “It’s a Tucker Torpedo.
Give him the loan.”
The Texan quite willingly signed his heirloom over.
An employee then drove the old car into the bank’s
underground garage and parked it. From time to time,
the employee would go, and turn over the engine, to keep
the car in good running condition, and gave it an
occasional waxing just to maintain it in pristine condition.
Two years later the Texan returned, and asked how
much he owed the bank. The loan officer started Emacs and
Lisp, and calculated the total debt as \$ 11,664.00.
\paragraph{Interest Calculation.}
\index{Interest!Compound}
Let us follow the calculation of the value accumulated
in the first year of compound interest at an 8\% rate
over \$ 10,000.00. Enter formula~\ref{eq:future-value} in
the Lisp Read Eval Print Loop:
\begin{quote}
\begin{verbatim}
* (* (expt (+ 1.0 0.08) 2) 10000)
11644.00
\end{verbatim}
\end{quote}
Observe that it was necessary to divide the
interest rate by 100, which produces 0.08.
\begin{figure}[!h]\index{define}
\begin{fmpage}{0.8\textwidth}
\begin{verbatim}
;; File: fvalue.lisp
(defun future-value(pv i n)
(* (expt (+ (/ i 100.0) 1) n)
pv)
);;end defun
\end{verbatim}
\end{fmpage}
\begin{fmpage}{0.8\textwidth}
\verb|* (load "fvalue.lisp")|\keys{Enter}\\
\verb|T|\\
\verb|* (future-value 10000 8 2)|\\
11664.001
\end{fmpage}
\caption{Future Value Program}
\label{Texan:parking}
\end{figure}
It is possible to define an operation that
calculates formula~\ref{eq:future-value}
given the arguments \verb|fv|, \verb|i|
and \verb|n|. The definition is given
in listing~\ref{Texan:parking}.
After typing the definition shown in listing~\ref{Texan:parking},
you must issue the \verb|C-x C-s| command to save the buffer.
In order to do this, keep the \keys{Ctrl} key pressed down and
hit the \keys{~x~} and \keys{~s~} keys in sequence.
In order to load the program into Lisp, keep the \keys{Alt} down
and press the \verb|x| key. The prompt \verb|M-x| will appear
in the minibuffer; type \verb|shell| at this prompt, as shown below.\\
\begin{fmpage}{0.8\textwidth}
\begin{verbatim}
;; File: fvalue.lisp
(defun future-value(pv i n)
(* (expt (+ (/ i 100.0) 1) n)
pv)
);;end defun
\end{verbatim}
\end{fmpage}
\begin{fmpage}{0.8\textwidth}
\verb|M-x shell|\keys{Enter}\\
\end{fmpage}
\verb||\\
When the shell chat starts, run the \verb|ros run| command
to start the Common Lisp compiler:
\begin{verbatim}
› ros run
* (load "fvalue.lisp")
T
* (future-value 10000 8 2)
11664.001y
\end{verbatim}
In listing~\ref{Texan:parking}, any text
between a semicolon and the end of
a line is considered a comment.
Therefore, \verb|;; File: fvalue.lisp|
is a comment. Likewise, \verb|;;end defun|
is a comment. Comments are ignored by
Lisp, and have the simple function of
helping users and programmers.
Now, let us see what Prolog adds to Common Lisp,
I mean, what Lisp programmers will gain by
having a Prolog compiler embedded into Common
Lisp. Here one can see a Prolog program for
calculating future values:
\index{Prolog!future value}
\begin{verbatim}
%% File: ?- consult('fvalue.pl')
period_of_time(2).
period_of_time(4).
period_of_time(8).
period_of_time(10).
futval(PV, I, N, FV) :- period_of_time(N),
FV is PV*(1+I/100)**N.
\end{verbatim}
\index{Prolog!comments}
In Prolog, comments are introduced by the \%
percent symbol, not by a semicolon, as in Lisp.
Variables are capitalized; thus, in the definition
of \verb|futval/4|, the symbols \verb|PV|, \verb|I|,
\verb|N|, and \verb|FV| are variables. Below you will
see an example of how to compile and execute
the \verb|'fvalue.pl'| program. The predicate
\verb|period_of_time/1| has four clauses. When
this predicate is called from \verb|futval/4| with the
\verb|period_of_time(N)| pattern, it unifies \verb|N|
with the first pattern, which makes \verb|N= 2|.
To make a long story short, there are many
options for the period of time \verb|N|, and Prolog
starts with the first choice.
The \verb|FV| future value is calculated for this choice
of \verb|N|, and the result is shown to the user. If the
first result is satisfactory, the user types
\verb|yes|, and Prolog stops searching for
solutions. If the user presses the semicolon
key, Prolog backtracks to the \verb|period_of_time(N)|
predicate, and chooses \verb|N=4|, which is
the second option. By repeatedly pressing
the semicolon, the user is able to obtain all solutions.
\begin{verbatim}
› rlwrap ros run
* (load "wamcompiler.lisp")
T
* (repl)
> ?- consult('fvalue.pl').
yes.
> ?- futval(10000, 8, N, FV).
N = 2
FV = 11664.001
?;
N = 4
FV = 13604.892
?;
N = 8
FV = 18509.309
?;
N = 10
FV = 21589.258
yes.
\end{verbatim}
\section{Mortgage}
A man with horns, legs and tail of a goat,
thick beard, snub nose and pointed ears entered
a real estate agency, and expressed his intention
of closing a deal. People fled in all directions,
thinking that Satan himself was paying them a visit.
Deardry seemed to be the only person who remained
calm. “What a ignorant, narrow minded, prejudiced
lot! I know you are not the devil. You are the
Great God Pan! What can I do for you?”
“I would like to buy a house in London.
I know that the city is made up of 32 Boroughs
and where I buy will make an enormous difference
to price, quality of life, and chances of increase
in capital value of the property.”
“Well, Sir, with our experience you can rest
assured that you will secure your ideal property.
Firstly we must decide on what type of property
fits your needs and where you want to be. You
may consider somewhere like Fulham, Chelsea,
Knightsbridge, Kensington or Mayfair.
I have properties in all these places. ”
“Chelsea! I like the name.”
“Chelsea is arguably one of the best residential
areas in London. It has benefited from it’s close
proximity to the west end of the city and is highly
sought after by overseas buyers looking to be located
in one of the most popular areas in central London.
At the moment, I can offer you a fantastic living
space in a four bedroomed flat situated behind
King's Road. The price is £10,500,000.”
“I don't have this kind of cash with me right now,
but can get it in a few months of working in a
circus. Meanwhile, can you arrange a mortgage for me? ”
“Yes, Yes I can help arrange mortgages in all 32 Boroughs
of London. Non-residents can have mortgages up to 70\% of
the purchase price. Do you have £3,150,000 pounds for the
down payment? In mortgage agreements, down payment is
the difference between the purchase price of a property
and the mortgage loan amount.”
“I know what down payment is. And yes, I can dispose
of £3,150,000 pounds.”
“A mortgage insurance is required for borrowers with
a down payment of less than 20\% of the home's purchase
price. That is not your case. Therefore, the balance of
the purchase price after the down payment is deducted
is the amount of your mortgage. Let us write a program
in Lisp to find out your estimated monthly payment.
The loan amount is £7,350,000 pounds. The interest rate
is 10\% a year. The length of the mortgage is 20 years.
That is the best I can do for you, I am afraid.
You are going to pay £97131.00 pounds a month for
ten years. After that, the balance of your debt
will be zero. But your visit is a surprise!”
The broker exclaimed. “ I never thought I would
ever see a true living god wanting to do property
deals in London.”
With that, Pan replied: “If property prices
were not so high, and interest rate so steep,
we would definitely be up for business more often.”
\includegraphics[scale=0.5]{figs-prefix/deuspan.jpg}
\paragraph{Loan Amortization.}
Amortization refers to the gradual reduction
of the loan principal through periodic payments.
\includegraphics{figs-prefix/agingshark.jpg}
Suppose you obtained a 20-year mortgage
for a \$ 100,000.00 principal at the interest
rate of 6\% a year. Calculate the monthly payments.
\paragraph{Amortization Formula.} Let $p$ be the
present value, $n$ the number of periods,
and $r$ be the
interest rate, i.e., the interest divided by 100.
In this case, the monthly payment for full
amortization is given by~\ref{eq:amortization}.
This formula is implemented in
listing~\ref{Pan:mortgage}.
\begin{equation}
\frac{r\times p\times(1+r)^n}{(1+r)^n - 1}
\label{eq:amortization}
\end{equation}
\begin{figure}[!h]\index{define}
\begin{fmpage}{0.9\textwidth}
\begin{verbatim}
;; File: (load "pmt.lisp")
(defun pmt(
p ;; present value
i ;; interest
n ;; number of periods
;; optional parameters
&optional (r (/ i 100.0))
(rn (expt (+ 1.0 r) n))
);;end of parameter list
(/ (* r p rn)
(- rn 1))
);;end of defun
\end{verbatim}
\end{fmpage}
\begin{fmpage}{0.9\textwidth}
\verb|(load "pmt.list")|\keys{Enter}\\
\verb|T|\\
\verb|(pmt (* 10500000.00 0.7) (/ 10.0 12) (* 20 12))|\keys{Enter}\\