]> gitweb.factorcode.org Git - factor.git/blob - extra/talks/tc-lisp-talk/tc-lisp-talk.factor
c0353a3e40eeafa5c0a828227909561e79644d65
[factor.git] / extra / talks / tc-lisp-talk / tc-lisp-talk.factor
1 ! Copyright (C) 2009 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: assocs combinators constructors eval help.markup kernel
4 multiline namespaces parser sequences sequences.private slides
5 vocabs.refresh words fry ;
6 IN: talks.tc-lisp-talk
7
8 CONSTANT: tc-lisp-slides
9 {
10     { $slide "Factor!"
11         { $url "http://factorcode.org" }
12         "Development started in 2003"
13         "Open source (BSD license)"
14         "Influenced by Forth, Lisp, and Smalltalk"
15         "Blurs the line between language and library"
16         "Interactive development"
17     }
18     { $slide "First, some examples"
19         { $code "3 weeks ago noon monday ." }
20         { $code "USE: roman 2009 >roman ." }
21         { $code ": average ( seq -- x )
22     [ sum ] [ length ] bi / ;" }
23         { $code "1 miles [ km ] undo >float ." }
24         { $code "[ readln eval>string print t ] loop" }
25     }
26     { $slide "XML Literals"
27         { $code
28         "USING: splitting xml.writer xml.syntax ;
29 { \"one\" \"two\" \"three\" }
30 [ [XML <item><-></item> XML] ] map
31 <XML <doc><-></doc> XML> pprint-xml"
32         }
33     }
34     { $slide "Differences between Factor and Lisp"
35         "Single-implementation language"
36         "Less nesting, shorter word length"
37         { "Dynamic reloading of code from files with " { $link refresh-all } }
38         "More generic protocols -- sequences, assocs, streams"
39         "More cross-platform"
40         "No standard for the language"
41         "Evaluates left to right"
42     }
43     { $slide "Terminology"
44         { "Words - functions" }
45         { "Vocabularies - collections of code in the same namespace" }
46         { "Quotations - blocks of code" { $code "[ dup reverse append ]" } }
47         { "Combinators - higher order functions" }
48         { "Static stack effect - known stack effect at compile-time" }
49     }
50     { $slide "Defining a word"
51         "Defined at parse time"
52         "Parts: name, stack effect, definition"
53         "Composed of tokens separated by whitespace"
54         { $code ": palindrome? ( string -- ? ) dup reverse = ;" }
55     }
56     { $slide "Non-static stack effect"
57         "Not a good practice, nor useful"
58         "Not compiled by the optimizing compiler"
59         { $code "100 <iota> [ ] each" }
60     }
61     { $slide "Module system"
62         "Code divided up into vocabulary roots"
63         "core/ -- just enough code to bootstrap Factor"
64         "basis/ -- optimizing compiler, the UI, tools, libraries"
65         "extra/ -- demos, unpolished code, experiments"
66         "work/ -- your works in progress"
67     }
68     { $slide "Module system (part 2)"
69         "Each vocabulary corresponds to a directory on disk, with documentation and test files"
70         { "Code for the " { $snippet "math" } " vocabulary: " { $snippet "~/factor/core/math/math.factor" } }
71         { "Documentation for the " { $snippet "math" } " vocabulary: " { $snippet "~/factor/core/math/math-docs.factor" } }
72         { "Unit tests for the " { $snippet "math" } " vocabulary: " { $snippet " ~/factor/core/math/math-tests.factor" } }
73     }
74     { $slide "Using a library"
75         "Each file starts with a USING: list"
76         "To use a library, simply include it in this list"
77         "Refreshing code loads dependencies correctly"
78     }
79     { $slide "Object system"
80         "Based on CLOS"
81         { "We define generic words that operate on the top of the stack with " { $link POSTPONE: GENERIC:  } " or on an implicit parameter with " { $link POSTPONE: HOOK: } }
82     }
83     { $slide "Object system example: shape protocol"
84         "In ~/factor/work/shapes/shapes.factor"
85         { $code "IN: shapes
86
87 GENERIC: area ( shape -- x )
88 GENERIC: perimeter ( shape -- x )"
89         }
90     }
91     { $slide "Implementing the shape protocol: circles"
92         "In ~/factor/work/shapes/circle/circle.factor"
93         { $code "USING: shapes constructors math
94 math.constants ;
95 IN: shapes.circle
96
97 TUPLE: circle radius ;
98 CONSTRUCTOR: <circle> circle ( radius -- obj ) ;
99 M: circle area radius>> sq pi * ;
100 M: circle perimeter radius>> pi * 2 * ;"
101         }
102     }
103     { $slide "Dynamic variables"
104         "Implemented as a stack of hashtables"
105         { "Useful words are " { $link get } ", " { $link set } }
106         "Input, output, error streams are stored in dynamic variables"
107         { $code "\"Today is the first day of the rest of your life.\"
108 [
109     readln print
110 ] with-string-reader"
111         }
112     }
113     { $slide "The global namespace"
114         "The global namespace is just the namespace at the bottom of the namespace stack"
115         { "Useful words are " { $link get-global } ", " { $link set-global } }
116         "Factor idiom for changing a particular namespace"
117         { $code "SYMBOL: king
118 global [ \"Henry VIII\" king set ] with-variables"
119         }
120         { $code "with-scope" }
121         { $code "namestack" }
122     }
123     { $slide "Hooks"
124         "Dispatch on a dynamic variable"
125         { $code "HOOK: computer-name os ( -- string )
126 M: macosx computer-name uname first ;
127 macosx \ os set-global
128 computer-name"
129         }
130     }
131     { $slide "Interpolate"
132         "Replaces variables in a string"
133         { $code
134 "\"Dawg\" \"name\" set
135 \"rims\" \"noun\" set
136 \"bling\" \"verb1\" set
137 \"roll\" \"verb2\" set
138 [
139     \"Sup ${name}, we heard you liked ${noun}, so we put ${noun} on your car so you can ${verb1} while you ${verb2}.\"
140     interpolate
141 ] with-string-writer print "
142         }
143     }
144     { $slide "Sequence protocol"
145         "All sequences obey a protocol of generics"
146         { "Is an object a " { $link sequence? } }
147         { "Getting the " { $link length } }
148         { "Accessing the " { $link nth  } " element" }
149         { "Setting an element - " { $link set-nth } }
150     }
151     { $slide "Examples of sequences in Factor"
152         "Arrays are mutable"
153         "Vectors are mutable and growable"
154         { "Arrays " { $code "{ \"abc\" \"def\" 50 }" } }
155         { "Vectors " { $code "V{ \"abc\" \"def\" 50 }" } }
156         { "Byte-arrays " { $code "B{ 1 2 3 }" } }
157         { "Byte-vectors " { $code "BV{ 11 22 33 }" } }
158     }
159     { $slide "Specialized arrays and vectors"
160         { "Specialized int arrays " { $code "int-array{ -20 -30 40 }" } }
161         { "Specialized uint arrays " { $code "uint-array{ 20 30 40 }" } }
162         { "Specialized float vectors " { $code "float-vector{ 20 30 40 }" } }
163         "35 others C-type arrays"
164     }
165     { $slide "Specialized arrays code"
166         "One line per array/vector"
167         { "In ~/factor/basis/specialized-arrays/float/float.factor"
168             { $code "<< \"float\" define-array >>" }
169         }
170         { "In ~/factor/basis/specialized-vectors/float/float.factor"
171             { $code "<< \"float\" define-vector >>" }
172         }
173     }
174
175     { $slide "Speciailzied arrays are implemented using functors"
176         "Like C++ templates"
177         "Eliminate boilerplate in ways other abstractions don't"
178         "Contains a definition section and a functor body"
179         "Uses the interpolate vocabulary"
180     }
181     { $slide "Functor for sorting"
182         { $code
183             "<FUNCTOR: define-sorting ( NAME QUOT -- )
184
185 NAME<=> DEFINES ${NAME}<=>
186 NAME>=< DEFINES ${NAME}>=<
187
188 WHERE
189
190 : NAME<=> ( obj1 obj2 -- <=> ) QUOT compare ;
191 : NAME>=< ( obj1 obj2 -- >=< )
192     NAME<=> invert-comparison ;
193
194 ;FUNCTOR>"
195         }
196     }
197     { $slide "Example of sorting functor"
198         { $code "USING: sorting.functor ;
199 << \"length\" [ length ] define-sorting >>"
200         }
201         { $code
202             "{ { 1 2 3 } { 1 2 } { 1 } }
203 [ length<=> ] sort"
204         }
205     }
206     { $slide "Combinators"
207         "Used to implement higher order functions (dataflow and control flow)"
208         "Compiler optimizes away quotations completely"
209         "Optimized code is just tight loops in registers"
210         "Most loops can be expressed with combinators or tail-recursion"
211     }
212     { $slide "Combinators that act on one value"
213         { $link bi }
214         { $code "10 [ 1 - ] [ 1 + ] bi" }
215         { $link tri }
216         { $code "10 [ 1 - ] [ 1 + ] [ 2 * ] tri" }
217     }
218     { $slide "Combinators that act on two values"
219         { $link 2bi }
220         { $code "10 1 [ - ] [ + ] 2bi" }
221         { $link bi* }
222         { $code "10 20 [ 1 - ] [ 1 + ] bi*" }
223         { $link bi@ }
224         { $code "5 9 [ sq ] bi@" }
225     }
226     { $slide "Sequence combinators"
227
228         { $link each }
229         { $code "{ 1 2 3 4 5 } [ sq . ] each" }
230         { $link map }
231         { $code "{ 1 2 3 4 5 } [ sq ] map" }
232         { $link filter }
233         { $code "{ 1 2 3 4 5 } [ even? ] filter" }
234     }
235     { $slide "Multiple sequence combinators"
236
237         { $link 2each }
238         { $code "{ 1 2 3 } { 10 20 30 } [ + . ] 2each" }
239         { $link 2map }
240         { $code "{ 1 2 3 } { 10 20 30 } [ + ] 2map" }
241     }
242     { $slide "Control flow: if"
243         { $link if }
244         { $code "10 random dup even? [ 2 / ] [ 1 - ] if" }
245         { $link when }
246         { $code "10 random dup even? [ 2 / ] when" }
247         { $link unless }
248         { $code "10 random dup even? [ 1 - ] unless" }
249     }
250     { $slide "Control flow: case"
251         { $link case }
252         { $code "ERROR: not-possible obj ;
253 10 random 5 <=> {
254     { +lt+ [ \"Less\" ] }
255     { +gt+ [ \"More\" ] }
256     { +eq+ [ \"Equal\" ] }
257     [ not-possible ]
258 } case"
259         }
260     }
261     { $slide "Fry"
262         "Used to construct quotations"
263         { "'Holes', represented by " { $snippet "_" } " are filled left to right" }
264         { $code "10 4 '[ _ + ] call" }
265         { $code "3 4 '[ _ sq _ + ] call" }
266     }
267     { $slide "Locals"
268         "When data flow combinators and shuffle words are not enough"
269         "Name your input parameters"
270         "Used in about 1% of all words"
271     }
272     { $slide "Locals example"
273         "Area of a triangle using Heron's formula"
274         { $code
275             ":: area ( a b c -- x )
276     a b c + + 2 / :> p
277     p
278     p a - *
279     p b - *
280     p c - * sqrt ;"
281         }
282     }
283     { $slide "Previous example without locals"
284         "A bit unwieldy..."
285         { $code
286             ": area ( a b c -- x )
287     [ ] [ + + 2 / ] 3bi
288     [ '[ _ - ] tri@ ] [ neg ] bi
289     * * * sqrt ;" }
290     }
291     { $slide "More idiomatic version"
292         "But there's a trick: put the lengths in an array"
293         { $code ": v-n ( v n -- w ) '[ _ - ] map ;
294
295 : area ( seq -- x )
296     [ 0 suffix ] [ sum 2 / ] bi
297     v-n product sqrt ;" }
298     }
299     { $slide "Implementing an abstraction"
300         { "Suppose we want to get the price of the customer's first order, but any one of the steps along the way could be a nil value (" { $link f } " in Factor):" }
301         { $code
302             "dup [ orders>> ] when"
303             "dup [ first ] when"
304             "dup [ price>> ] when"
305         }
306     }
307     { $slide "This is hard with mainstream syntax!"
308         { $code
309             "var customer = ...;
310 var orders = (customer == null ? null : customer.orders);
311 var order = (orders == null ? null : orders[0]);
312 var price = (order == null ? null : order.price);" }
313     }
314     { $slide "An ad-hoc solution"
315         "Something like..."
316         { $code "var price = customer.?orders.?[0].?price;" }
317     }
318     { $slide "Macros in Factor"
319         "Expand at compile-time"
320         "Return a quotation to be compiled"
321         "Can express non-static stack effects"
322         "Not as widely used as combinators, 60 macros so far"
323         { $code "{ 1 2 3 4 5 } 5 firstn" }
324     }
325     { $slide "A macro solution"
326         "Returns a quotation to the compiler"
327         "Constructed using map, fry, and concat"
328         { $code "MACRO: plox ( seq -- quot )
329     [
330         '[ dup _ when ]
331     ] map [ ] concat-as ;"
332         }
333     }
334     { $slide "Macro example"
335         "Return the caaar of a sequence"
336         { "Return " { $snippet "f" } " on failure" }
337         { $code ": caaar ( seq/f -- x/f )
338     {
339         [ first ]
340         [ first ]
341         [ first ]
342     } plox ;"
343         }
344         { $code "{ { f } } caaar" }
345         { $code "{ { { 1 2 3 } } } caaar" }
346     }
347     { $slide "Smart combinators"
348         "Use stack checker to infer inputs and outputs"
349         "Even fewer uses than macros"
350         { $code "{ 1 10 20 34 } sum" }
351         { $code "[ 1 10 20 34 ] sum-outputs" }
352         { $code "[ 2 2 [ even? ] both? ] [ + ] [ - ] smart-if" }
353     }
354     { $slide "Fibonacci"
355         "Not tail recursive"
356         "Call tree is huge"
357         { $code ": fib ( n -- x )
358     dup 1 <= [
359         [ 1 - fib ] [ 2 - fib ] bi +
360     ] unless ;"
361         }
362         { $code "36 <iota> [ fib ] map ." }
363     }
364     { $slide "Memoized Fibonacci"
365         "Change one word and it's efficient"
366         { $code "MEMO: fib ( n -- x )
367     dup 1 <= [
368         [ 1 - fib ] [ 2 - fib ] bi +
369     ] unless ;"
370         }
371         { $code "36 <iota> [ fib ] map ." }
372     }
373     { $slide "Destructors"
374         "Deterministic resource disposal"
375         "Any step can fail and we don't want to leak resources"
376         "We want to conditionally clean up sometimes -- if everything succeeds, we might wish to retain the buffer"
377     }
378
379     { $slide "Example in C"
380         { $code
381 "void do_stuff()
382 {
383     void *obj1, *obj2;
384     if(!(*obj1 = malloc(256))) goto end;
385     if(!(*obj2 = malloc(256))) goto cleanup1;
386     ... work goes here...
387 cleanup2: free(*obj2);
388 cleanup1: free(*obj1);
389 end: return;
390 }"
391     }
392     }
393     { $slide "Example: allocating and disposing two buffers"
394         { $code ": do-stuff ( -- )
395     [
396         256 malloc &free
397         256 malloc &free
398         ... work goes here ...
399     ] with-destructors ;"
400         }
401     }
402     { $slide "Example: allocating two buffers for later"
403         { $code ": do-stuff ( -- )
404     [
405         256 malloc |free
406         256 malloc |free
407         ... work goes here ...
408     ] with-destructors ;"
409         }
410     }
411     { $slide "Example: disposing of an output port"
412         { $code "M: output-port dispose*
413     [
414         {
415             [ handle>> &dispose drop ]
416             [ buffer>> &dispose drop ]
417             [ port-flush ]
418             [ handle>> shutdown ]
419         } cleave
420     ] with-destructors ;"
421         }
422     }
423     { $slide "Rapid application development"
424         "We lost the dice to Settlers of Catan: Cities and Knights"
425         "Two regular dice, one special die"
426         { $vocab-link "dice" }
427     }
428     { $slide "The essence of Factor"
429         "Nicely named words abstract away the stack, leaving readable code"
430         { $code ": surround ( seq left right -- seq' )
431     swapd 3append ;"
432         }
433         { $code ": glue ( left right middle -- seq' )
434     swap 3append ;"
435         }
436         { $code HEREDOC: xyz
437 "a" "b" "c" 3append
438 "a" """""""" surround
439 "a" "b" ", " glue
440 xyz
441         }
442     }
443     { $slide "C FFI demo"
444         "Easy to call C functions from Factor"
445         "Handles C structures, C types, callbacks"
446         "Used extensively in the Windows and Unix backends"
447         { $code
448             "FUNCTION: double pow ( double x, double y ) ;
449 2 5.0 pow ."
450         }
451     }
452     { $slide "Windows win32 example"
453         { $code
454 "M: windows gmt-offset
455     ( -- hours minutes seconds )
456     \"TIME_ZONE_INFORMATION\" <c-object>
457     dup GetTimeZoneInformation {
458         { TIME_ZONE_ID_INVALID [
459             win32-error
460         ] }
461         { TIME_ZONE_ID_STANDARD [
462             TIME_ZONE_INFORMATION-Bias
463         ] }
464     } case neg 60 /mod 0 ;"
465         }
466     }
467     { $slide "Struct and function"
468         { $code "C-STRUCT: TIME_ZONE_INFORMATION
469     { \"LONG\" \"Bias\" }
470     { { \"WCHAR\" 32 } \"StandardName\" }
471     { \"SYSTEMTIME\" \"StandardDate\" }
472     { \"LONG\" \"StandardBias\" }
473     { { \"WCHAR\" 32 } \"DaylightName\" }
474     { \"SYSTEMTIME\" \"DaylightDate\" }
475     { \"LONG\" \"DaylightBias\" } ;"
476         }
477         { $code "FUNCTION: DWORD GetTimeZoneInformation (
478     LPTIME_ZONE_INFORMATION
479         lpTimeZoneInformation
480 ) ;"
481         }
482
483     }
484     { $slide "Cocoa FFI"
485         { $code "IMPORT: NSAlert [
486     NSAlert -> new
487     [ -> retain ] [
488         \"Raptor\" <CFString> &CFRelease
489         -> setMessageText:
490     ] [
491         \"Look out!\" <CFString> &CFRelease
492         -> setInformativeText:
493     ] tri -> runModal drop
494 ] with-destructors"
495         }
496     }
497     { $slide "Deployment demo"
498         "Vocabularies can be deployed"
499         "Standalone .app on Mac"
500         "An executable and dll on Windows"
501         { $vocab-link "webkit-demo" }
502     }
503     { $slide "Interesting programs"
504         { $vocab-link "terrain" }
505         { $vocab-link "gpu.demos.raytrace" }
506         { $vocab-link "gpu.demos.bunny" }
507     }
508     { $slide "Factor's source tree"
509         "Lines of code in core/: 9,500"
510         "Lines of code in basis/: 120,000"
511         "Lines of code in extra/: 51,000"
512         "Lines of tests: 44,000"
513         "Lines of documentation: 44,500"
514     }
515     { $slide "VM trivia"
516         "Lines of C++ code: 12860"
517         "Generational garbage collection"
518         "Non-optimizing compiler"
519         "Loads an image file and runs it"
520     }
521     { $slide "Why should I use Factor?"
522         "More abstractions over time"
523         "We fix reported bugs quickly"
524         "Stackable, fluent language"
525         "Supports extreme programming"
526         "Beer-friendly programming"
527     }
528     { $slide "Questions?"
529     }
530 }
531
532 : tc-lisp-talk ( -- )
533     tc-lisp-slides "TC Lisp talk" slides-window ;
534
535 MAIN: tc-lisp-talk