This repository has been archived by the owner on Jul 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSmooth CoffeeScript.html
17049 lines (16268 loc) · 651 KB
/
Smooth CoffeeScript.html
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0073)http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" manifest="smooth.manifest">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="./Smooth CoffeeScript_files/SmoothCoffeeScript.css" type="text/css" media="all">
<title>Smooth CoffeeScript</title>
</head>
<body>
<!--
<div class="menu">
<div class="rdbWrapper" data-show-read="1" data-show-send-to-kindle="1" data-show-print="1" data-show-email="1" data-orientation="0" data-version="1" data-bg-color="#fffce6"><div id="readabilityEmbedContainer" name="readabilityEmbedContainer" style="height: 35px; padding: 0; margin: 0; z-index: 50000"> <iframe id="readabilityEmbedIFrame-0" name="readabilityEmbedIFrame-0" scrolling="no" frameborder="0" style="height: 35px; overflow: hidden; border-width: 0; white-space: nowrap; width: 100%;" src="./Smooth CoffeeScript_files/embed.html"></iframe> </div></div><script type="text/javascript" async="" src="./Smooth CoffeeScript_files/embed.js"></script><script type="text/javascript">(function() {var s = document.getElementsByTagName("script")[0],rdb = document.createElement("script"); rdb.type = "text/javascript"; rdb.async = true; rdb.src = document.location.protocol + "//www.readability.com/embed.js"; s.parentNode.insertBefore(rdb, s); })();</script>
<input class="field" type="button" onclick="document.getElementById('globalWrapper').style.maxWidth = document.getElementById('globalWrapper').style.maxWidth===''?'600px':''" value="Adjust Width">
<input class="field" type="button" onclick="window.open('https://github.com/autotelicum/Smooth-CoffeeScript/archives/master')" value="Download Source">
<a href="http://github.com/autotelicum/Smooth-CoffeeScript/" target="_blank"><img style="position: absolute; top: 0; right: 0; border: 0;" src="./Smooth CoffeeScript_files/687474703a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f677261795f3664366436642e706e67" alt="Fork me on GitHub"></a>
</div>
-->
<div id="globalWrapper" onclick="void(0)">
<div class="center"><img class="embedded" src="./Smooth CoffeeScript_files/SmoothCoverWithSolutions.jpg" alt="figure img/SmoothCoverWithSolutions.jpg" style="width: 70%; height: auto;"></div>
<h1 class="title">
<span class="sans"><span class="large">Smooth CoffeeScript</span></span>
</h1>
<div class="center">
<div class="author">
E. Hoigaard
</div>
<div class="Publishers">
<span class="large"><a class="URL" href="http://autotelicum.github.com/Smooth-CoffeeScript">http://autotelicum.github.com/Smooth-CoffeeScript</a></span>
</div>
<div class="Dedication">
An introduction to CoffeeScript programming with<br>
an emphasis on clarity, abstraction and verification.<span class="large"><br>
<div class="vspace" style="height: 25pheight%;">
</div>
<br>
</span>The book is <a class="URL" href="http://creativecommons.org/licenses/by/3.0/">freely</a> available, and may be used (as a whole or in parts)<br>
in any way you see fit, as long as credit is given to the original author.<br>
<a class="URL" href="http://eloquentjavascript.net/">Based on Eloquent JavaScript by Marijn Haverbeke</a>.<span class="large"><br>
<div class="vspace" style="height: 25pheight%;">
</div>
<br>
1<sup>st</sup> edition, 3<sup>rd</sup> revision & illustrations © 2554 <a class="URL" href="http://www.accesstoinsight.org/history.html#fn-1">BE</a> / 2011 <a class="URL" href="http://www.accesstoinsight.org/history.html#fn-2">CE</a>.<br>
<a class="URL" href="http://www.publicdomainpictures.net/view-image.php?image=11133&picture=ostriches-look">Public domain cover photo</a>.
</span></div></div>
<div class="fulltoc">
<div class="tocheader">
Table of Contents
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Part-I">Part I: Preface</a>
</div>
<div class="tocindent">
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-1">Chapter: Software</a>
</div>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Part-II">Part II: Language</a>
</div>
<div class="tocindent">
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-2">Chapter: <span class="sans">Introduction</span></a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-3">Chapter: <span class="sans">Basic CoffeeScript</span></a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-4">Chapter: <span class="sans">Functions</span></a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-5">Chapter: <span class="sans">Data Structures</span></a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-6">Chapter: <span class="sans">Error Handling</span></a>
</div>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Part-III">Part III: Paradigm</a>
</div>
<div class="tocindent">
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-7">Chapter: <span class="sans">Functional Programming</span></a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-8">Chapter: <span class="sans">Searching</span></a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-9">Chapter: <span class="sans">Object Orientation</span></a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-10">Chapter: <span class="sans">Regular Expressions</span></a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Chapter-11">Chapter: <span class="sans">Modularity</span></a>
</div>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Part-IV">Part IV: Appendix</a>
</div>
<div class="tocindent">
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Appendix-A">Appendix: <span class="sans">Language Extras</span></a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Appendix-B">Appendix: <span class="sans">Binary Heaps</span></a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Appendix-C">Appendix: Performance</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Appendix-D">Appendix: Command Line Utility</a>
</div>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Part-V">Part V: Reference and Index</a>
</div>
<div class="tocindent">
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Appendix-E">Appendix: Reference</a>
</div>
<div class="tocindent">
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Section--1">Section: Language Reference</a>
</div>
<div class="tocindent">
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--1">Subsection: General</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--2">Subsection: Embedded JavaScript</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--3">Subsection: Functions</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--4">Subsection: Objects and arrays</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--5">Subsection: Lexical Scoping and Variable Safety</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--6">Subsection: If, Else, Unless, and Conditional Assignment</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--7">Subsection: Splats</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--8">Subsection: Loops and Comprehensions</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--9">Subsection: Array Slicing and Splicing with Ranges</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--10">Subsection: Everything is an Expression</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--11">Subsection: Operators and Aliases</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--12">Subsection: Existential Operator</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--13">Subsection: Classes, Inheritance, and Super</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--14">Subsection: Destructuring Assignment</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--15">Subsection: Function binding</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--16">Subsection: Switch/When/Else</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--17">Subsection: Try/Catch/Finally</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--18">Subsection: String Interpolation, Heredocs, and Block Comments</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--19">Subsection: Chained Comparisons</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--20">Subsection: Extended Regular Expressions</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--21">Subsection: Reserved Words</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--22">Subsection: Underscore</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--23">Subsection: qc.js</a>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#toc-Subsection--24">Subsection: Additional Words</a>
</div>
</div>
</div>
</div>
<div class="toc">
<a class="Link" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#Index">Index</a>
</div>
</div>
<h1 class="Part">
<a class="toc" name="toc-Part-I">Part I.</a> Preface
</h1>
<div class="Addchap">
Foreword<a class="Label" name="chap:Foreword"> </a>
</div>
<div class="Standard">
CoffeeScript is a lucid evolution of JavaScript created by Jeremy Ashkenas. This book attempts to be an evolution of “Eloquent JavaScript” by Marijn Haverbeke. Apart from the major change in explaining CoffeeScript instead of JavaScript, numerous other changes have been made and sections have been added, edited or removed.
</div>
<div class="Standard">
Everything that is expressed in this book is therefore solely the responsibility of the editor. In the sense of open source software, this book is a <a class="URL" href="http://en.wikipedia.org/wiki/Fork_(software_development)">fork</a>. To read the excellent original JavaScript work as it was intended by its author refer to <a class="URL" href="http://eloquentjavascript.net/">Eloquent JavaScript by Marijn Haverbeke</a>.
</div>
<div class="Standard">
You do not need to know JavaScript but after reading <span class="sans">Smooth CoffeeScript</span> you can in <a class="URL" href="http://autotelicum.github.com/Smooth-CoffeeScript/literate/js-intro.html">JavaScript Basics</a> by Rebecca Murphey find an overview that can be helpful when debugging or using JavaScript libraries.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
The program examples in this book use a prelude file in addition to the CoffeeScript environment. It includes the Underscore functional library, the Coffeekup <span class="versalitas"><span class="small">HTML</span></span><span class="default"> markup, <tt>ws</tt> server-side WebSockets and <tt>qc</tt>, a QuickCheck based testing library. These libraries extend CoffeeScript with useful abstractions and testing tools to keep focus on the task at hand instead of distracting boilerplate code.</span>
</div>
<div class="Standard">
While it is possible to express programs from a very small set of language primitives, it quickly becomes tedious and error prone to do so. The approach taken here is to include a broader set of functional building blocks as if they were a native part of the programming language. By thinking in terms of these higher level constructs more complex problems can be handled with less effort.
</div>
<div class="Standard">
To ensure correctness testing is required. This is especially true when developing reusable algorithms in a dynamic and untyped language. By integrating QuickCheck style test cases as soon as functions are introduced, it is intended that writing tests and declaring assumptions become a seamless part of writing software.
</div>
<div class="Standard">
<p><br>
</p>
</div>
<div class="Standard">
CoffeeScript is available in browsers and environments where JavaScript is available. The screenshots below show CoffeeScript running the same web server and client application on Mac OS X, Windows and iOS.
</div>
<div class="Standard">
<div class="medskip"> </div>
</div>
<div class="Standard">
<div class="center">
<img class="embedded" src="./Smooth CoffeeScript_files/TadaOnMacOSX.png" alt="figure img/TadaOnMacOSX.png" style="width: 70%; height: auto;">
</div>
</div>
<div class="Standard">
<div class="center">
<img class="embedded" src="./Smooth CoffeeScript_files/TadaOnWin7.png" alt="figure img/TadaOnWin7.png" style="width: 70%; height: auto;">
</div>
</div>
<div class="Standard">
<div class="center">
<img class="embedded" src="./Smooth CoffeeScript_files/TadaOnIOS.png" alt="figure img/TadaOnIOS.png" style="width: 70%; height: auto;">
</div>
</div>
<div class="Standard">
The CoffeeScript below shows the brevity of the self-contained application from the screenshots. It contains an <span class="versalitas"><span class="small">HTML</span></span><span class="default"> 5 web page in Coffeekup markup and its own <span class="versalitas"></span></span><span class="small">HTTP</span><span class="default"> web server. The page has a Canvas element with a drawing of the ‘Seed of Life’. Coffeekup is a few hundred lines of CoffeeScript. No frameworks. No JavaScript. Pure and smooth.</span>
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">require ’./prelude’
webpage = kup.render ->
doctype 5
html ->
head ->
meta charset: ’utf-8’
title ’My drawing | My awesome website’
style ’’’
body {font-family: sans-serif}
header, nav, section, footer {display: block}
’’’
coffeescript ->
draw = (ctx, x, y) ->
circle = (ctx, x, y) ->
ctx.beginPath()
ctx.arc x, y, 100, 0, 2*Math.PI, false
ctx.stroke()
ctx.strokeStyle = ’rgba(255,40,20,0.7)’
circle ctx, x, y
for angle in [0...2*Math.PI] by 1/3*Math.PI
circle ctx, x+100*Math.cos(angle),
y+100*Math.sin(angle)
window.onload = ->
canvas = document.getElementById ’drawCanvas’
context = canvas.getContext ’2d’
draw context, 300, 200
body ->
header -> h1 ’Seed of Life’
canvas id: ’drawCanvas’, width: 600, height: 400
http = require ’http’
server = http.createServer (req, res) ->
show "#{req.client.remoteAddress} #{req.method} #{req.url}"
res.writeHead 200, ’Content-Type’: ’text/html’
res.write webpage
res.end()
server.listen 3389
show ’Server running at’
show server.address()
</pre>
</div>
</div>
<h1 class="Chapter">
<a class="toc" name="toc-Chapter-1"></a>Software
</h1>
<div class="Standard">
<span class="sans">Smooth CoffeeScript</span> is about the CoffeeScript language, see <a class="URL" href="http://autotelicum.github.com/Smooth-CoffeeScript/literate/install-notes.html">Quick CoffeeScript Install</a> or refer to the websites for further installation information. This should get you started:
</div>
<div class="Standard">
<div class="medskip"> </div>
</div>
<ul>
<li>
The CoffeeScript language (1.1.3 / MIT) from <a class="URL" href="http://www.coffeescript.org/">Jeremy Ashkenas</a>
</li>
<li>
The Underscore library (1.1.0.FIX / MIT) included in <a class="URL" href="http://jashkenas.github.com/coffee-script/documentation/docs/underscore.html">CoffeeScript</a>
</li>
<li>
The Coffeekup library (0.3.1 / MIT) from <a class="URL" href="http://coffeekup.org/">Maurice Machado</a>
</li>
<li>
Translated <tt>ws</tt> WebSockets (MIT) from <a class="URL" href="https://github.com/ncr/node.ws.js">Jacek Becela</a>
</li>
<li>
The <tt>qc</tt> testing library<span class="FootOuter"><span class="SupFootMarker" onclick="void(0)"> [A] </span><span class="HoverFoot"><span class="SupFootMarker"> [A] </span>This library is only used to test functionality. The CoffeeScript applications in <span class="sans">Smooth CoffeeScript</span> do not depend on it. CoffeeScript is a new language and tools like <tt>qc</tt> depend on legacy code written in JavaScript.</span></span> (2009 / BSD) from <a class="URL" href="https://bitbucket.org/darrint/qc.js/">Darrin Thompson</a>
</li>
</ul>
<div class="Standard">
<div class="medskip"> </div>
</div>
<div class="Standard">
The required libraries have been adapted for standard CoffeeScript and are included in the <div class="listing">
<pre class="listing">src/prelude
</pre>
</div>
directory. Underscore, <tt>ws</tt> and Coffeekup are written in CoffeeScript and they are small enough to read and understand in a short time — at least after you have read this book.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
To set up your own working environment follow the steps described <a class="URL" href="http://autotelicum.github.com/Smooth-CoffeeScript/literate/install-notes.html">here</a> or at <a class="URL" href="http://jashkenas.github.com/coffee-script/#installation">coffeescript.org</a><span class="FootOuter"><span class="SupFootMarker" onclick="void(0)"> [B] </span><span class="HoverFoot"><span class="SupFootMarker"> [B] </span>The CoffeeScript examples have been tested on Mac OS X 10.6 and on Windows 7 with the prebuilt node installers.</span></span>. If you use Windows then you can adapt the prelude to default to your preferred web browser. You can also find instructions there for how to enable WebSockets if your browser requires it.
</div>
<div class="Standard">
Then set up your text editor to support CoffeeScript, you can find several on the <a class="URL" href="https://github.com/jashkenas/coffee-script/wiki/Text-editor-plugins">CoffeeScript wiki</a>. For example to use the <a class="URL" href="https://github.com/jashkenas/coffee-script-tmbundle">TextMate bundle</a> with the cross-platform <a class="URL" href="http://www.sublimetext.com/2">Sublime Text 2 editor</a>, unpack the bundle in a CoffeeScript directory under Packages. This setup gives you syntax highlighting, code snippets, and code completion.
</div>
<div class="Standard">
You can add a build file to get execution of CoffeeScript with the press of a button. Name the file CoffeeScript.sublime-build and change the path according to you operating system and install location. Something like:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">{
"cmd": ["/Users/username/bin/coffee", "$file"],
"file_regex": "^Error: In (...*?),
Parse error on line ([0-9]*):?",
"selector": "source.coffee"
}
</pre>
</div>
</div>
<div class="Standard">
Finally open a command-line in a terminal and type (again adjust for your platform)
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">cd path-to-smooth-coffeescript/src
coffee -r ./prelude
</pre>
</div>
</div>
<div class="Standard">
Then you have a CoffeeScript Read-Eval-Print-Loop (REPL) at your disposal. Read the <a class="URL" href="http://jashkenas.github.com/coffee-script/#installation">usage section</a> for more information on the CoffeeScript compiler. You can run samples with <div class="listing">
<pre class="listing">coffee filename.coffee
</pre>
</div>
.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
<span class="sans">Smooth CoffeeScript</span> comes in two editions; with and without solutions. Complete by chapter source code files are in the src directory. A copy of all files are in src-no-solutions, these files have stops where you can insert your own solutions.
</div>
<div class="Standard">
To get the most out of the book: Start your text editor and in src-no-solutions open the source code file for the chapter you are reading. If you have a wide-screen display then arrange your windows so the book is on one side and the text editor on the other. Then you can read and run the samples, see the results, experiment with the code and solve the exercises.
</div>
<div class="Standard">
If you make copies of the files you work on then you can easily undo experiments. If you get stuck with an exercise then copy my solution from the file in the src directory and study it a bit before moving on. Note that in some of the source files you have to indent your solutions to match the surrounding code.
</div>
<div class="Standard">
Both editions and accompanying source files can be downloaded from: <a class="URL" href="http://autotelicum.github.com/Smooth-CoffeeScript/">http://autotelicum.github.com/Smooth-CoffeeScript/</a>
</div>
<h1 class="Part">
<a class="toc" name="toc-Part-II">Part II.</a> Language
</h1>
<h1 class="Chapter">
<a class="toc" name="toc-Chapter-2"></a>Introduction <a class="Label" name="chap:Introduction"> </a>
</h1>
<div class="Standard">
When personal computers were first introduced, most of them came equipped with a simple programming language, usually a variant of <span class="versalitas">BASIC</span>. Interacting with the computer was closely integrated with this language, and thus every computer-user, whether he wanted to or not, would get a taste of it. Now that computers have become plentiful and cheap, typical users do not get much further than clicking things with a mouse. For most people, this works very well. But for those of us with a natural inclination towards technological tinkering, the removal of programming from every-day computer use presents something of a barrier.
</div>
<div class="Standard">
Fortunately, as an effect of developments in the World Wide Web, it so happens that every computer equipped with a modern web-browser also has an environment for programming JavaScript which can easily be adapted to an environment for CoffeeScript. In today’s spirit of not bothering the user with technical details, it is kept well hidden, but a web-page can make it accessible, and use it as a platform for learning to program. You can find such an environment in the menu on <a class="URL" href="http://autotelicum.github.com/Smooth-CoffeeScript/coffeescript.org">coffeescript.org</a> select ‘Try CoffeeScript’ or use the ‘load’ button below the examples.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
<div class="vspace" style="height: -3pt;">
</div>
</div>
<blockquote class="Quote">
<i>I do not enlighten those who are not eager to learn, nor arouse those who are not anxious to give an explanation themselves. If I have presented one corner of the square and they cannot come back to me with the other three, I should not go over the points again.</i>
</blockquote>
<div class="Dictum">
<span class="sans"><span class="footnotesize">Confucius</span></span>
</div>
<div class="Standard">
<div class="bigskip"> </div>
</div>
<div class="Standard">
Besides explaining CoffeeScript, this book tries to be an introduction to the basic principles of programming. Programming, it turns out, is hard. The fundamental rules are, most of the time, simple and clear. But programs, while built on top of these basic rules, tend to become complex enough to introduce their own rules, their own complexity. Because of this, programming is rarely simple or predictable. As Donald Knuth, who is something of a founding father of the field, says, it is an <i>art</i>.
</div>
<div class="Standard">
To get something out of this book, more than just passive reading is required. Try to stay sharp, make an effort to solve the exercises, and only continue on when you are reasonably sure you understand the material that came before.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
<div class="vspace" style="height: -3pt;">
</div>
</div>
<blockquote class="Quote">
<i>The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs.</i>
</blockquote>
<div class="Dictum">
<span class="sans"><span class="footnotesize">Joseph Weizenbaum, <i>Computer Power and Human Reason</i></span></span><br>
</div>
<div class="Standard">
<div class="bigskip"> </div>
</div>
<div class="Standard">
A program is many things. It is a piece of text typed by a programmer, it is the directing force that makes the computer do what it does, it is data in the computer’s memory, yet it controls the actions performed on this same memory. Analogies that try to compare programs to objects we are familiar with tend to fall short, but a superficially fitting one is that of a machine. The gears of a mechanical watch fit together ingeniously, and if the watchmaker was any good, it will accurately show the time for many years. The elements of a program fit together in a similar way, and if the programmer knows what he is doing, the program will run without crashing.
</div>
<div class="Standard">
A computer is a machine built to act as a host for these immaterial machines. Computers themselves can only do stupidly straightforward things. The reason they are so useful is that they do these things at an incredibly high speed. A program can, by ingeniously combining many of these simple actions, do very complicated things.
</div>
<div class="Standard">
To some of us, writing computer programs is a fascinating game. A program is a building of thought. It is costless to build, weightless, growing easily under our typing hands. If we get carried away, its size and complexity will grow out of control, confusing even the one who created it. This is the main problem of programming. It is why so much of today’s software tends to crash, fail, screw up.
</div>
<div class="Standard">
When a program works, it is beautiful. The art of programming is the skill of controlling complexity. The great program is subdued, made simple in its complexity.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
Today, many programmers believe that this complexity is best managed by using only a small set of well-understood techniques in their programs. They have composed strict rules about the form programs should have, and the more zealous among them will denounce those who break these rules as <i>bad</i> programmers.
</div>
<div class="Standard">
What hostility to the richness of programming! To try to reduce it to something straightforward and predictable, to place a taboo on all the weird and beautiful programs. The landscape of programming techniques is enormous, fascinating in its diversity, still largely unexplored.
</div>
<div class="Standard">
It is certainly littered with traps and snares, luring the inexperienced programmer into all kinds of horrible mistakes, but that only means you should proceed with caution, keep your wits about you. As you learn, there will always be new challenges, new territory to explore. The programmer who refuses to keep exploring will surely stagnate, forget his joy, lose the will to program (and become a manager).
</div>
<div class="Standard">
As far as I am concerned, the definite criterion for a program is whether it is correct. Efficiency, clarity, and size are also important, but how to balance these against each other is always a matter of judgement, a judgement that each programmer must make for himself. Rules of thumb are useful, but one should never be afraid to break them.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
In the beginning, at the birth of computing, there were no programming languages. Programs looked something like this:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">00110001 00000000 00000000 00110001 00000001 00000001
00110011 00000001 00000010 01010001 00001011 00000010
00100010 00000010 00001000 01000011 00000001 00000000
01000001 00000001 00000001 00010000 00000010 00000000
01100010 00000000 00000000
</pre>
</div>
</div>
<div class="Standard">
That is a program to add the numbers from one to ten together, and print out the result (1 + 2 + … + 10 = 55). It could run on a very simple kind of computer. To program early computers, it was necessary to set large arrays of switches in the right position, or punch holes in strips of cardboard and feed them to the computer. You can imagine how this was a tedious, error-prone procedure. Even the writing of simple programs required much cleverness and discipline, complex ones were nearly inconceivable.
</div>
<div class="Standard">
Of course, manually entering these arcane patterns of bits (which is what the 1s and 0s above are generally called) did give the programmer a profound sense of being a mighty wizard. And that has to be worth something, in terms of job satisfaction.
</div>
<div class="Standard">
Each line of the program contains a single instruction. It could be written in English like this:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing"><span class="number-left">1</span>Store the number 0 in memory location 0
<span class="number-left">2</span>Store the number 1 in memory location 1
<span class="number-left">3</span>Store the value of memory location 1 in location 2
<span class="number-left">4</span>Subtract the number 11 from the value in location 2
<span class="number-left">5</span>If the value in memory location 2 is the number 0,
<span class="number-left"> </span> continue with instruction 9
<span class="number-left">6</span>Add the value of memory location 1 to location 0
<span class="number-left">7</span>Add the number 1 to the value of memory location 1
<span class="number-left">8</span>Continue with instruction 3
<span class="number-left">9</span>Output the value of memory location 0
</pre>
</div>
</div>
<div class="Standard">
While that is more readable than the binary soup, it is still rather unpleasant. It might help to use names instead of numbers for the instructions and memory locations:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">Set ’total’ to 0
Set ’count’ to 1
[loop]
Set ’compare’ to ’count’
Subtract 11 from ’compare’
If ’compare’ is zero, continue at [end]
Add ’count’ to ’total’
Add 1 to ’count’
Continue at [loop]
[end]
Output ’total’
</pre>
</div>
</div>
<div class="Standard">
At this point it is not too hard to see how the program works. Can you? The first two lines give two memory locations their starting values: <div class="listing">
<pre class="listing">total
</pre>
</div>
will be used to build up the result of the program, and <div class="listing">
<pre class="listing">count
</pre>
</div>
keeps track of the number that we are currently looking at. The lines using <div class="listing">
<pre class="listing">compare
</pre>
</div>
are probably the weirdest ones. What the program wants to do is see if <div class="listing">
<pre class="listing">count
</pre>
</div>
is equal to 11, in order to decide whether it can stop yet. Because the machine is so primitive, it can only test whether a number is zero, and make a decision (jump) based on that. So it uses the memory location labelled <div class="listing">
<pre class="listing">compare
</pre>
</div>
to compute the value of <div class="listing">
<pre class="listing">count - 11
</pre>
</div>
, and makes a decision based on that value. The next two lines add the value of <div class="listing">
<pre class="listing">count
</pre>
</div>
to the result, and increment <div class="listing">
<pre class="listing">count
</pre>
</div>
by one every time the program has decided that it is not 11 yet. Here is the same program in CoffeeScript:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">total = 0
count = 1
while count <= 10
total += count
count += 1
show total
</pre>
</div>
</div>
<div class="Standard">
This gives us a few more improvements. Most importantly, there is no need to specify the way we want the program to jump back and forth anymore. The magic word <div class="listing">
<pre class="listing">while
</pre>
</div>
takes care of that. It continues executing the lines indented below it as long as the condition it was given holds: <div class="listing">
<pre class="listing">count <= 10
</pre>
</div>
, which means ‘<div class="listing">
<pre class="listing">count
</pre>
</div>
is less than or equal to <div class="listing">
<pre class="listing">10
</pre>
</div>
’. Apparently, there is no need anymore to create a temporary value and compare that to zero. This was a stupid little detail, and the power of programming languages is that they take care of stupid little details for us.
</div>
<div class="Standard">
This can also be expressed in a shorter form in CoffeeScript:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">total = 0
total += count for count in [1..10]
show total
</pre>
</div>
</div>
<div class="Standard">
The <div class="listing">
<pre class="listing">for
</pre>
</div>
and <div class="listing">
<pre class="listing">in
</pre>
</div>
words goes through the range of numbers from 1 to 10 <div class="listing">
<pre class="listing">[1..10]
</pre>
</div>
, assigning each number in turn to <div class="listing">
<pre class="listing">count
</pre>
</div>
. Each value in <div class="listing">
<pre class="listing">count
</pre>
</div>
is then added to <div class="listing">
<pre class="listing">total
</pre>
</div>
.
</div>
<div class="Standard">
Finally, here is what the program could look like if we happened to have the convenient operation <div class="listing">
<pre class="listing">sum
</pre>
</div>
available, which computes the sum of a collection of numbers similar to the mathematical notation <span class="formula"><span class="limits"><span class="limit">∑</span></span><span class="scripts"><sup class="script">10</sup><sub class="script"><i>n</i> = 1</sub></span><i>n</i></span>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">show sum [1..10]
</pre>
</div>
</div>
<div class="Standard">
Another possibility is to have functions attached to datatypes. Here a sum function is attached to an array, giving the sum of the elements in the array.
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">show [1..10].sum()
</pre>
</div>
</div>
<div class="Standard">
The moral of this story, then, is that the same program can be expressed in long and short, unreadable and readable ways. The first version of the program was extremely obscure, while the last ones are almost English: <div class="listing">
<pre class="listing">show
</pre>
</div>
the <div class="listing">
<pre class="listing">sum
</pre>
</div>
of the numbers from <div class="listing">
<pre class="listing">1
</pre>
</div>
to <div class="listing">
<pre class="listing">10
</pre>
</div>
. (We will see in later chapters how to build things like <div class="listing">
<pre class="listing">sum
</pre>
</div>
.)
</div>
<div class="Standard">
A good programming language helps the programmer by providing a more abstract way to express himself. It hides uninteresting details, provides convenient building blocks (such as the <div class="listing">
<pre class="listing">while
</pre>
</div>
construct), and, most of the time, allows the programmer to add building blocks himself (such as the <div class="listing">
<pre class="listing">sum
</pre>
</div>
operation).
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
JavaScript is the language that is, at the moment, mostly being used to do all kinds of clever and horrible things with pages on the World Wide Web. JavaScript is also used for scripting in <a class="URL" href="http://en.wikipedia.org/wiki/JavaScript#Uses_outside_web_pages">a variety of applications and operating systems</a>. Of special note is server-side JavaScript (SSJS), where the server portion of a web application is written in JavaScript, so a full application can be expressed in one programming language. CoffeeScript generates standard JavaScript code and can therefore be used in environments where standard JavaScript is accepted. It means that both browser portions and server portions can be written in CoffeeScript.
</div>
<div class="Standard">
CoffeeScript is a new language so it remains to be seen how popular it becomes for general application development, but if you are interested in programming, CoffeeScript is definitely a useful language to learn. Even if you do not end up doing much web programming, the mind-bending programs in this book will always stay with you, haunt you, and influence the programs you write in other languages.
</div>
<div class="Standard">
There are those who will say <i>terrible</i> things about JavaScript. Many of these things are true. When I was for the first time required to write something in JavaScript, I quickly came to despise the language. It would accept almost anything I typed, but interpret it in a way that was completely different from what I meant. This had a lot to do with the fact that I did not have a clue what I was doing, but there is also a real issue here: JavaScript is ridiculously liberal in what it allows. The idea behind this design was that it would make programming in JavaScript easier for beginners. In actuality, it mostly makes finding problems in your programs harder, because the system will not point them out to you.
</div>
<div class="Standard">
However, the flexibility of the language is also an advantage. It leaves space for a lot of techniques that are impossible in more rigid languages, and it can be used to overcome some of JavaScript’s shortcomings. After learning it properly, and working with it for a while, I have really learned to <i>like</i> this language. CoffeeScript repairs many of the confusing and cumbersome aspects of JavaScript, while keeping its underlying flexibility and beauty. It is <i>doubleplusgood</i>.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
Most chapters in this book contain quite a lot of code<span class="FootOuter"><span class="SupFootMarker" onclick="void(0)"> [C] </span><span class="HoverFoot"><span class="SupFootMarker"> [C] </span>‘Code’ is the substance that programs are made of. Every piece of a program, whether it is a single line or the whole thing, can be referred to as ‘code’.</span></span>. In my experience, reading and writing code is an important part of learning to program. Try to not just glance over these examples, but read them attentively and understand them. This can be slow and confusing at first, but you will quickly get the hang of it. The same goes for the exercises. Do not assume you understand them until you have actually written a working solution.
</div>
<div class="Standard">
Because of the way the web works, it is always possible to look at the JavaScript programs that people put in their web-pages. This can be a good way to learn how some things are done. Because most web programmers are not ‘professional’ programmers, or consider JavaScript programming so uninteresting that they never properly learned it, a lot of the code you can find like this is of a <i>very</i> bad quality. When learning from ugly or incorrect code, the ugliness and confusion will propagate into your own code, so be careful who you learn from. Another source of programs are CoffeeScript projects hosted on open source services such as <a class="URL" href="https://github.com/">github</a>.
</div>
<h1 class="Chapter">
<a class="toc" name="toc-Chapter-3"></a>Basic CoffeeScript:<br>
values, variables, and control flow<a class="Label" name="chap:Basic-CoffeeScript"> </a>
</h1>
<div class="Standard">
Inside the computer’s world, there is only data. That which is not data, does not exist. Although all data is in essence just a sequence of bits<span class="FootOuter"><span class="SupFootMarker" onclick="void(0)"> [D] </span><span class="HoverFoot"><span class="SupFootMarker"> [D] </span>Bits are any kinds of two-valued things, usually described as <div class="listing">
<pre class="listing">0
</pre>
</div>
s and <div class="listing">
<pre class="listing">1
</pre>
</div>
s. Inside the computer, they take forms like a high or low electrical charge, a strong or weak signal, a shiny or dull spot on the surface of a CD.</span></span>, and is thus fundamentally alike, every piece of data plays its own role. In CoffeeScript’s system, most of this data is neatly separated into things called value<a class="IndexReference" name="entry-value-0" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#index-value">↓</a>s. Every value has a type, which determines the kind of role it can play. There are six basic types of values: Numbers, strings, booleans, objects, functions, and undefined values.
</div>
<div class="Standard">
To create a value, one must merely invoke its name. This is very convenient. You do not have to gather building material for your values, or pay for them, you just call for one and <i>woosh</i>, you have it. They are not created from thin air, of course. Every value has to be stored somewhere, and if you want to use a gigantic amount of them at the same time you might run out of computer memory. Fortunately, this is only a problem if you need them all simultaneously. As soon as you no longer use a value, it will dissipate, leaving behind only a few bits. These bits are recycled to make the next generation of values.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
Values of the type number<a class="IndexReference" name="entry-number-0" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#index-number">↓</a> are, as you might have deduced, numeric values. They are written the way numbers are usually written:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">144
</pre>
</div>
</div>
<div class="Standard">
Enter that in the console, and the same thing is printed in the output window. The text you typed in gave rise to a number value, and the console took this number and wrote it out to the screen again. In a case like this, that was a rather pointless exercise, but soon we will be producing values in less straightforward ways, and it can be useful to ‘try them out’ on the console to see what they produce.
</div>
<div class="Standard">
This is what <div class="listing">
<pre class="listing">144
</pre>
</div>
looks like in bits<span class="FootOuter"><span class="SupFootMarker" onclick="void(0)"> [E] </span><span class="HoverFoot"><span class="SupFootMarker"> [E] </span>If you were expecting something like <div class="listing">
<pre class="listing">10010000
</pre>
</div>
here — good call, but read on. CoffeeScript’s numbers are not stored as integers.</span></span>: <div class="listing">
<pre class="listing">01000000 01100010 00000000 00000000 00000000 00000000 00000000 00000000
</pre>
</div>
</div>
<div class="Standard">
The number above has 64 bits. Numbers in CoffeeScript always do. This has one important repercussion: There is a limited amount of different numbers that can be expressed. With three decimal digits, only the numbers 0 to 999 can be written, which is 10<sup>3</sup> = 1000 different numbers. With 64 binary digits, 2<sup>64</sup> different numbers can be written. This is a lot, more than 10<sup>19</sup> (a one with nineteen zeroes).
</div>
<div class="Standard">
Not all whole numbers below 10<sup>19</sup> fit in a CoffeeScript number though. For one, there are also negative numbers, so one of the bits has to be used to store the sign of the number. A bigger issue is that non-whole numbers must also be represented. To do this, 11 bits are used to store the position of the decimal dot within the number.
</div>
<div class="Standard">
That leaves 52 bits<span class="FootOuter"><span class="SupFootMarker" onclick="void(0)"> [F] </span><span class="HoverFoot"><span class="SupFootMarker"> [F] </span>Actually, 53, because of a trick that can be used to get one bit for free. Look up the ‘IEEE 754’ format if you are curious about the details.</span></span>. Any whole number less than 2<sup>52</sup>, which is over 10<sup>15</sup>, will safely fit in a CoffeeScript number. In most cases, the numbers we are using stay well below that, so we do not have to concern ourselves with bits at all. Which is good. I have nothing in particular against bits, but you <i>do</i> need a terrible lot of them to get anything done. When at all possible, it is more pleasant to deal with bigger things.
</div>
<div class="Standard">
Fractional numbers are written by using a dot.
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">9.81
</pre>
</div>
</div>
<div class="Standard">
For very big or very small numbers, one can also use ‘scientific’ notation by adding an <div class="listing">
<pre class="listing">e
</pre>
</div>
, followed by the exponent of the number:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">2.998e8
</pre>
</div>
</div>
<div class="Standard">
Which is 2.998 <span class="default"><span class="formula">⋅</span>10<sup>8</sup> = 299</span> <span class="default">800</span> <span class="default">000. </span>
</div>
<div class="Standard">
Calculations with whole numbers (also called integers) that fit in 52 bits are guaranteed to always be precise. Unfortunately, calculations with fractional numbers are generally not. Like <span class="formula"><i>π</i></span> (pi) can not be precisely expressed by a finite amount of decimal digits, many numbers lose some precision when only 64 bits are available to store them. This is a shame, but it only causes practical problems in very specific situations<span class="FootOuter"><span class="SupFootMarker" onclick="void(0)"> [G] </span><span class="HoverFoot"><span class="SupFootMarker"> [G] </span>An example of this, if <div class="listing">
<pre class="listing">p = 1/3
</pre>
</div>
then <div class="listing">
<pre class="listing">6*p
</pre>
</div>
is equal to <div class="listing">
<pre class="listing">2
</pre>
</div>
. However <div class="listing">
<pre class="listing">p+p+p+p+p+p
</pre>
</div>
is not equal to <div class="listing">
<pre class="listing">2
</pre>
</div>
because the minute rounding errors increase for every addition. This happens in the <div class="listing">
<pre class="listing">for
</pre>
</div>
loop shown in the <a class="Reference" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#chap:Foreword">Preface↑</a>. It is a general issue with floating point approximations and not a bug in CoffeeScript. A way of dealing with it is to test if a number is inside a narrow interval instead of testing for an exact match.</span></span>. The important thing is to be aware of it, and treat fractional digital numbers as approximations, not as precise values.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
The main thing to do with numbers is arithmetic. Arithmetic operations such as addition or multiplication take two number values and produce a new number from them. Here is what they look like in CoffeeScript: <div class="listing">
<pre class="listing">100 + 4 * 11
</pre>
</div>
</div>
<div class="Standard">
The <div class="listing">
<pre class="listing">+
</pre>
</div>
and <div class="listing">
<pre class="listing">*
</pre>
</div>
symbols are called operators. The first stands for addition, and the second for multiplication. Putting an operator between two values will apply<a class="IndexReference" name="entry-applying-0" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#index-applying">↓</a> it to those values, and produce a new value.
</div>
<div class="Standard">
Does the example mean ‘add 4 and 100, and multiply the result by 11’, or is the multiplication done before the adding? As you might have guessed, the multiplication happens first. But, as in mathematics, this can be changed by wrapping the addition in parentheses<a class="IndexReference" name="entry-()-0" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#index-()">↓</a>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">(100 + 4) * 11
</pre>
</div>
</div>
<div class="Standard">
For subtraction, there is the <div class="listing">
<pre class="listing">-
</pre>
</div>
operator, and division can be done with <div class="listing">
<pre class="listing">/
</pre>
</div>
. When operators appear together without parentheses, the order in which they are applied is determined by the precedence<a class="IndexReference" name="entry-precedence-0" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#index-precedence">↓</a> of the operators. The first example shows that multiplication has a higher precedence than addition. Division and multiplication always come before subtraction and addition. When multiple operators with the same precedence appear next to each other (<div class="listing">
<pre class="listing">1 - 1 + 1
</pre>
</div>
) they are applied left-to-right.
</div>
<div class="Standard">
Try to figure out what value this produces, and then run it to see if you were correct…
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">115 * 4 - 4 + 88 / 2
</pre>
</div>
These rules of precedence are not something you should worry about. When in doubt, just add parentheses.
</div>
<div class="Standard">
There is one more arithmetic operator which is probably less familiar to you. The <div class="listing">
<pre class="listing">%
</pre>
</div>
symbol is used to represent the modulo<a class="IndexReference" name="entry-modulo-0" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#index-modulo">↓</a> operation. <div class="listing">
<pre class="listing">X
</pre>
</div>
modulo <div class="listing">
<pre class="listing">Y
</pre>
</div>
is the remainder of dividing <div class="listing">
<pre class="listing">X
</pre>
</div>
by <div class="listing">
<pre class="listing">Y
</pre>
</div>
. For example <div class="listing">
<pre class="listing">314 % 100
</pre>
</div>
is <div class="listing">
<pre class="listing">14
</pre>
</div>
, <div class="listing">
<pre class="listing">10 % 3
</pre>
</div>
is <div class="listing">
<pre class="listing">1
</pre>
</div>
, and <div class="listing">
<pre class="listing">144 % 12
</pre>
</div>
is <div class="listing">
<pre class="listing">0
</pre>
</div>
. Modulo has the same precedence as multiplication and division.
</div>
<div class="Standard">
<div class="center">
<span class="formula">○•○</span>
</div>
</div>
<div class="Standard">
The next data type is the string<a class="IndexReference" name="entry-string-0" href="http://autotelicum.github.com/Smooth-CoffeeScript/SmoothCoffeeScript.html#index-string">↓</a>. Its use is not as evident from its name as with numbers, but it also fulfills a very basic role. Strings are used to represent text, the name supposedly derives from the fact that it strings together a bunch of characters. Strings are written by enclosing their content in quotes:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing">’Patch my boat with chewing gum.’
</pre>