-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
534 lines (532 loc) · 21.5 KB
/
index.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
<html>
<head>
<title>Try LiveScript</title>
<meta name="viewport" content="user-scalable=yes, width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="try-livescript.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="libs/jquery.console.js"></script>
<script type="text/javascript" src="libs/livescript.js"></script>
<script type="text/javascript" src="libs/prelude.js"></script>
<script type="text/javascript" src="try-livescript.js"></script>
</head>
<body>
<div id="ls-console">
</div>
<div id="lessons">
<section x-path="welcome">
<section x-path="wlecome/fancy">
<meta name='x-pre' value='{fold, all, sqrt, filter, sum} = require \prelude-ls'>
<h3>Got 15 mins to try LiveScript?</h3>
<p>
Try typing these out and see what happens (click to insert):
<code class='prompt'>fold (+), 0, [1 to 100]</code>
<pre class='prompt'>
is-prime = (x) ->
x > 1 and all (x %), [2 to sqrt x]
do -> [1 to 100] |> sum . filter is-prime
</pre>
<pre class='prompt' x-no-history>
html <- $.get window.location.href
alert "This page has #{$ html .text!.split '' .length} characters!"
</pre>
</p>
<p>
LiveScript is a language that compiles to JavaScript. It has many features that assist in functional programming. Comparing to JavaScript or CoffeeScript, LiveScript syntax is noise-less and more flexible.
</p>
<p>
Type <code class='prompt'>next!</code> to go to the next step.
</p>
<footer>
Console is powered by
<a href="http://github.com/chrisdone/jquery-console">jquery-console</a>.
</footer>
</section>
<section x-path="welcome/expressions">
<h3>Expressions</h3>
<p>
Almost everything in LiveScript is an expression:
</p>
<p>
<code class="prompt">2 * (10 + 27 / 3)</code>
</p>
<p>
<code class="prompt">if 2 * 2 == 4 then "two times two is four" else "impossible"</code>
</p>
<p>
<code class="prompt">true and false</code>
</p>
<p>
String interpolation works with any expression.
</p>
<p>
<pre class="prompt" x-no-linefeed>
"This window's width is: #outer-width
and this document's title is: #{document.query-selector "title" .text-content}"
</pre>
The language supports multi-line strings.
</p>
<p>
Type <code class='prompt' x-no-history>next!</code> to go to the next step. or
<code class='prompt' x-no-history>back!</code> to go to the previous step.
</p>
</section>
<section x-path="welcome/variables">
<h3>Variables</h3>
<p>
We define a variable by <code class='prompt'>x = 42</code>
JavaScript <code>var</code> is not needed.
</p>
<p>
You can use dashes in the name of your variables and functions:
<code class='prompt'>planet-name = 'Saturn'</code>. This is equivalent and will be compiled to
<code>planetName = 'Saturn';</code>
</p>
</section>
<section x-path="welcome/functions">
<h3>Functions</h3>
<p>
Defining functions is very lightweight:
<code class='prompt'>add = (x, y) -> x + y</code>
</p>
<p>
We don't need paranthesis for invoking functions:
<code class='prompt'>add 5, 18</code>
</p>
<p>
You can also call functions infix using backticks:
<code class='prompt'>5 `add` 18</code>
</p>
<p>
Some examples:
</p>
<p>
<code class="prompt">double = (x) -> x * 2</code>
</p>
<p>
<code class="prompt">double-small-number = (x) -> if x < 100 then x * 2 else x</code>
</p>
<p>
<code class="prompt">hello = (name) -> "Hello #name"</code>
</p>
<p>
The result of the last expression inside a function body will be returned as its output. You can use <code>return</code> to force returns earlier:
<pre class="prompt">
fact = (n) ->
return undefined if n < 1
return 1 if n == 1
n * fact n - 1
</pre>
</p>
</section>
<section x-path="welcome/lists">
<meta name="x-pre" value="{odd, even} = require \prelude-ls">
<h3>Lists</h3>
<p>
You can use list comprehension to produce new lists:
<code class='prompt'>[1 to 10]</code> or
<code class='prompt'>[i * 2 for i in [1 to 10]]</code>
</p>
<p>
Filtering: <code class='prompt'>[i if odd i for i in [1 to 10]]</code>
</p>
<p>
Nested comprehensions produce a flat list:
<code class='prompt'>[i * j for i in [1 to 10] for j in [-10 to -1]]</code>
</p>
<p>
For example here is the list of all Pythagorian triples that are less than 10:
<pre class='prompt'>
[[a, b, c] for a in [1 to 10]
for b in [1 to 10]
for c in [1 to 10]
when a*a + b*b == c*c
]
</pre>
</p>
<footer>
Pythagorian triples: <a class='info' href="http://www.mathsisfun.com/pythagorean_triples.html">http://www.mathsisfun.com/pythagorean_triples.html</a>
</footer>
</section>
</section>
<section x-path="pattern-matching">
<section x-path="pattern-matching/tuples">
<h3>Pattern Matching</h3>
<p>
This is a tuple: <code class='prompt'>color = ['white', 0xffffff]</code>
</p>
<p>
You can use pattern matching to extract values from a tuple, list or an object.
<pre class='prompt'>
[name, hex] = color
"Hexadecimal value for color #name is: 0x#{hex.to-string 16}"
</pre>
</p>
<p>
This is a list: <code class='prompt'>list = ['A', 'B', 'C', 'D', 'E', 'F']</code>
</p>
<p>
You can use pattern matching on the lists:
<code class='prompt'>[head, ...rest] = ['A', 'B', 'C', 'D', 'E', 'F']</code>
</p>
</section>
<section x-path="pattern-matching/lists">
<meta name="x-pre" value="{empty} = require \prelude-ls">
<h3>Destructuring Lists</h3>
<p>
Two lists can be concatenated using <code>++</code> operator (<code class="prompt">one-to-ten = [1,2,3,4,5] ++ [6,7,8,8,10]</code>).
<pre class="prompt">
[head, ...rest] = ['A', 'B', 'C', 'D', 'E', 'F']
[head] ++ rest
</pre>
<code class="prompt">[head] ++ rest</code> is the original list.
</p>
<p>
Pattern matching is especially useful for self documenting the code.
</p>
<p>
Using everything we know so far and a little bit of recursion we can implement the all famous quicksort function:
<pre class="prompt">
quicksort = ([x, ...xs]:list) ->
return [] if list.length == 0
smaller-sorted = quicksort [a for a in xs when a <= x]
bigger-sorted = quicksort [a for a in xs when a > x]
smaller-sorted ++ [x] ++ bigger-sorted
</pre>
Try it out: <code class="prompt">quicksort [7, 91, 22, 5, 2, 1, 83]</code>
</p>
<footer>
Quicksort from: <a class="info" href="http://learnyouahaskell.com/recursion#quick-sort">http://learnyouahaskell.com/recursion</a>
</footer>
</section>
<section x-path="pattern-matching/objects">
<h3>Objects</h3>
<p>
Here's a simple object literal:
<pre class='prompt'>
saturn =
name: 'saturn'
mass: 568
orbital-period: 29
distance-from-sum:
min: 9.05
max: 10.12
</pre>
Pattern matching also works on objets:
<pre x-no-linefeed class="prompt" x-pre="
saturn =
name: 'saturn'
mass: 568
orbital-period: 29
distance-from-sun:
min: 9.05
max: 10.12">
{distance-from-sun: {min, max}} = saturn
"Perihelion: #min AU, Aphelion: #max AU"
</pre>
</p>
<p>
You can use pattern matching to import certain properties from a node module:
<pre x-no-linefeed class="prompt">
{pi, sin} = require 'prelude-ls'
sin pi/2
</pre>
prelude.ls is LiveScript standard library, we are goting to explore it a little bit later.
</p>
</section>
</section>
<section x-path="functions">
<section x-path="functions/currying">
<h3>Currying</h3>
<p>
A curried function can be called with less arguments that defined with, and then it will return a partially applied function.
This means that it returns a function whose arguments are those which you didn't supply.
</p>
<p>
Curried functions are defined by long arrows <code>--></code>, for example:
<code class="prompt">add = (x, y) --> x + y</code>, now
<code class="prompt">add5 = add 5</code> is a function that takes a number and adds 5 to it: <code class="prompt">add5 20</code>
</p>
<p>
Binary infix operators can also be partially applied:
<code class="prompt">ten-times = (10 *)</code>
</p>
<p>
<code class="prompt">devide-by-ten = (/ 10)</code>
</p>
<p>
If the function takes only one parameter, you can ignore the parameter in arguments list and use the special keyword <code>it</code> to refernece the parameter in the body of the function:
<code class='prompt'>square = -> it * it</code>
</p>
<footer>
Currying is named after 20th century mathematician <a href="http://en.wikipedia.org/wiki/Haskell_Curry" class="info">Haskell Curry</a>.
</footer>
</section>
<section x-path="functions/currying-advanced">
<meta name="x-pre" value='pi = Math.PI' />
<meta name="x-pre" value='{map} = require \prelude-ls' />
<h3>Why currying?</h3>
<p>
We can truncate a decimal number to different precisions.
<pre x-no-linefeed class="prompt">
truncate = (precision, i) -->
((i * 10**precision) - (i * 10**precision) % 1) / (10**precision)
</pre>
<code>truncate</code> takes two arguments: precision (that is the number of digits after decimal point) and the actual input that's the number that needs to be truncateed: <code class="prompt">truncate 2, pi</code>
</p>
<p>
Now we can easily create different versions of the truncate function:
</p>
<p>
<code class="prompt">truncate0 = truncate 0</code> that returns a whole number.
</p>
<p>
<code class="prompt">truncate1 = truncate 1</code> that truncates with one decimal point; etc.
</p>
<p>
Now take a look at this example that returns a list of numbers that are π truncateed with different precisions:
<pre x-no-linefeed class="prompt">[0 to 6].map(-> truncate it).map(-> it pi)</pre>
OK what's going on here? Let's break this expression down to understand it:
</p>
<p>
<code class="prompt">[0 to 6]</code> creates a list of numbers from 0 to 6.
</p>
<p>
<code class="prompt">[0 to 6].map(-> truncate it)</code> creates a list of curried truncate functions. Each item in this list is the truncate function with a different precision. For example <code>[0 to 6].map(-> truncate it)[2] == truncate 2</code>
</p>
<p>
<code>map(-> it pi)</code> applies every curried truncate functions to π.
</p>
<p>
Note that in each step <code>it</code> refers to one element of the list that was produced in the previous step. <code>it</code> in <code>[0 to 6].map(-> truncate it)</code> is a number (0 to 6) and <code>it</code> in <code>map(-> it pi)</code> is a function.
</p>
<p>
Once we get used to LiveScript and its standard library (prelude.ls), we will omit these <code>it</code>s using the curried form of <code>map</code> from prelude.ls:
<pre x-no-linefeed class="prompt">[0 to 6] |> map truncate |> map (<| pi)</pre>
</p>
</section>
<section x-path="functions/invocation">
<h3>Function Invocation</h3>
<p>
Here's a function that takes no argument and always returns 5: <code class="prompt">five = -> 5</code>. Invoke this function by: <code class="prompt">five!</code>
</p>
<p>
Use <code>do</code> to invoke an anonymous closure automatically:
<pre class="prompt" x-no-history>
do ->
area = screen.width * screen.height
alert "Your screen area is #area pixels"
</pre>
Note the scope of <code class="prompt">area</code> variable: it is not accesible outside the anonynous closure.
</p>
<p>
This is a colsure that remembers the number of times that it was invoked:
<pre class="prompt">
say-hello = do ->
i = 0
(greetings) ->
i := i + 1
"#i - Hello #{greetings}"
</pre>
We use <code>:=</code> to modify a variable that is defined in the outer scope.
</p>
</section>
<section x-path="functions/composition">
<meta name="x-pre" value="[f, g] = [(3 *), (10 +)]">
<meta name="x-pre" value="length = (s) -> s.length">
<meta name="x-pre" value="odd = (i) -> i % 2 == 1">
<h3>Function Composition</h3>
<p>
Composing allows you to create new functions by composing them out of a series of functions. If <code>f</code> and <code>g</code> are two functions then
<code>f . g</code> or <code>f << g</code> is equivalent to <code>f(g(x))</code> and <code>f >> g</code> is equivalent to <code>g(f(x))</code>
</p>
<p>
For example, given: <code class="prompt">f = (3 *)</code> and <code class="prompt">g = (10 +)</code>
</p>
<p>
<code x-no-history class="prompt">(f << g) 5</code>
is equivalent to
<code class="prompt">f(g(5))</code> or
<code>(3 *)(10 + 5) = (3 *) 15 = 45</code>
</p>
<p>
<code x-no-history class="prompt">(f >> g) 5</code>
is equivalent to
<code class="prompt">g(f(5))</code> or
<code>(10 +)(3 * 5) = (10 +) 15 = 25</code>
</p>
<p>
For an example take the length function:
<code class="prompt">length = (s) -> s.length</code> that returns the length of its input string. We can write its type with this notation:
<pre>length :: String -> Number</pre>
</p>
<p>
And odd function that returns true if its input is an odd number:
<code class="prompt">odd = (i) -> i % 2 == 1</code>; its type is:
<pre>odd :: Number -> Boolean</pre>
</p>
<p>
Now the type of <code class="prompt">is-length-odd = (length >> odd)</code> is:
<pre>is-length-odd :: String -> Boolean</pre>
Its input is the input of the first function and its output is the output of the second function.
</p>
<p>
Generally:
<pre>
f :: a -> b
g :: b -> c
(f >> g) :: a -> c
</pre>
</p>
</section>
<section x-path="functions/piping">
<meta name="x-pre" value="{sum, odd, filter, map, sqrt} = require \prelude-ls">
<h3>Piping</h3>
<p>
We grew up learning that the arguments of a function are palced at its right side: <code>Sin(θ)</code>; but in LiveScript
we can pipe an argument to a function by <code>|></code> from its left side:
<pre x-no-linefeed class="prompt">[1 to 10] |> sum</pre>
</p>
<p>
<code><|</code> evaluates its right side and pipes the result to the function at its left:
<pre class="prompt" x-no-linefeed x-no-history>sum <| map sqrt, [1 to 10]</pre>
</p>
<p>
For example, the following snippet generates a list of 10 random integers between 0 and 100:
<pre class="prompt" x-no-linefeed>[1 to 10] |> map (-> Math.round <| Math.random! * 100)</pre>
</p>
<p>
We pipe the list of numbers between 1 to 10 to map function.
</p>
<p>
map invokes the anonynous function <code>(-> Math.round <| Math.random! * 100)</code> for each item in the list.
</p>
<p>
The function ignores its input (the number), produces a random floating point number between 0 and 100 (<code>Math.random! * 100</code>) and rounds it.
</p>
</section>
<section x-path="functions/callbacks">
<meta name='x-pre' value='{map} = require \prelude-ls'>
<h3>Backcalls</h3>
<p>
Backcalls allow you to unnest callbacks. They are defined using arrows pointed to the left.
</p>
<p>
The content length of this page:
<pre x-no-linefeed class="prompt">html <- $.get window.location.href ; alert html.length</pre>
</p>
<p>
Using backcalls is a way for avoiding callback hell in
serial asynchronous sequences:
<pre class="prompt" x-no-history>
html <- $.get window.location.href
$script = $ '<html/>' .html html .find "script[src*='libs/']:first"
content <- $.get ($script .attr 'src')
alert "The content size of the first external script is #{content.length}"
</pre>
</p>
</section>
</section>
<section x-path="prelude.ls">
<section x-path="prelude.ls/basics">
<meta name='x-pre' value='{map, filter, odd, even, fold, concat-map, zip} = require \prelude-ls'>
<h3>perlude.ls</h3>
<p>
prelude.ls is the recommended base library for LiveScript.
It defines many utility functions for working with lists and objects.
We've already seen <code>map</code> and <code>filter</code>:
<pre x-no-linefeed class="prompt">[1 to 10] |> map (* 2) |> filter (> 10)</pre>
Here we are doubling each integer between 1 and 10 and then filtering the result for numbers that are greater than 10.
</p>
<p>
<code>concat-map</code> produces a flattened list;
The below snippet produces a list of lists using map:
<pre x-no-linefeed class="prompt">[1 to 5] |> map (i) -> [1 to i]</pre>
But it will produce a list of just numbers using concat-map:
<pre x-no-linefeed class="prompt">[1 to 5] |> concat-map (i) -> [1 to i]</pre>
</p>
</section>
<section x-path="prelude.ls/zip">
<meta name='x-pre' value='{map, filter, odd, even, fold, concat-map, zip} = require \prelude-ls'>
<h3>Zipping</h3>
<p>
<code>zip</code> zips two lists together! Producing a list of tuples:
<pre x-no-linefeed class="prompt">
alphabet = [65 to 90] |> map String.from-char-code
alphabet `zip` [1 to 26]
</pre>
</p>
<p>
You can pipe the output of the previous zip to a filter function to only select the even letters in the alphabet:
<pre x-no-linefeed class="prompt">
alphabet `zip` [1 to 26] |> (filter ([_, i]) -> even i) |> (map ([a, _]) -> a)
</pre>
You might go fancier and use a shorter expression that does the same job:
<pre x-no-linefeed class="prompt">
alphabet `zip` [1 to 26] |> filter (.1) >> even |> map (.0)
</pre>
<code class="prompt">(.1) >> even</code> is a function composition.
<code class="prompt">(.1)</code> is a function that returns the second element of its input tuple (or array): <code class="prompt">(.1) [1, 2, 3]</code>
</p>
<p>
Remember that <code class="prompt">alphabet `zip` [1 to 26]</code> is a list of tuples like <code>[['A', 1], ['B', 2], ...]</code>. <code>filter (.1) >> even</code> applies <code class="prompt">(.1) >> even</code> function on every element of this list. <code class="prompt">(.1) >> even</code> takes a tuple in its input, extracts its second element, and checks if it's even: for example:
<code class="prompt">(.1) >> even <| ['B', 2]</code>
</p>
</section>
<section x-path="prelude.ls/fold">
<meta name='x-pre' value='{map, filter, odd, even, fold, concat-map, zip} = require \prelude-ls'>
<h3>Folding</h3>
<p>
Fold has many names, JavaScript calls it reduce, C# programmers know it as aggregate. Fold is very powerful, every other function that operates on lists in prelude.ls can be written using folds.
</p>
<p>
For example here's how we sum all the elements inside an array:
<pre class="prompt" x-no-linefeed>
fold ((acc, a) -> acc + a), 0, [1 to 10]
</pre>
fold takes three parameters:
<ul>
<li>A function that takes the accumulated result and the next element to be folded</li>
<li>The seed (initial value, must have the same type as the expected output)</li>
<li>List to be folded</li>
</ul>
In our type notation:
<pre>
fold :: ((acc, a) -> acc), acc, [a]
</pre>
</p>
<p>
Since <code>(+)</code> is a function, we can shorten our sum expression to:
<pre class="prompt" x-no-linefeed>
fold (+), 0, [1 to 10]
</pre>
So we can define sum function like:
<pre class="prompt" x-no-linefeed>
sum = fold (+), 0
</pre>
<code>sum</code> takes an array, sums it elements and returns the sum: <code class="prompt">sum [1 to 100]</code>
</p>
<p>
It takes some time to fully appreciate the power of fold, if you have not used functional programming before. <a href="http://preludels.com">prelude.ls</a> comes with a tons of other utility functions!
</p>
</section>
</section>
<section x-path="fin">
<section x-path="fin/done!">
<meta name='x-pre' value='{map, filter, odd, even, fold, concat-map, zip} = require \prelude-ls'>
<h3>Excited?</h3>
<p>
We just scratched the surface of LiveScript in this tutorial.
Check out <a href="http://livescript.net">http://livescript.net</a> for full documentation.
</p>
<p>
Cheers!
</p>
</section>
</section>
</div>
<nav class="back-next">
<a class="prev-step" href="#"><< <span>Back</span></a>
<a class="next-step" href="#"><span>Next</span> >></a>
</nav>
</body>
</html>