source: project/wiki/new-chapter1 @ 8740

Last change on this file since 8740 was 8740, checked in by svnwiki, 12 years ago

Changes applied for John Cowan ( through svnwiki:

added some TODOs, gave my views on a few here and there

File size: 21.3 KB
1== Getting started with Chicken
3TODO: this page is a revision and expansion of the existing Chapter 1
4of the Chicken manual. The goal is to give an overview of the whole
5system, and to give the new user some recipes for common use cases.
6I know this is somewhat verbose, and would be happy to eliminate
7unnecessary verbiage, but I do think the content shown here is
8worthwhile. Your mileage, of course, might vary :-) -- vincent
10''(This document describes version 3.0.0)'' TODO: the version number
11should be moved from here to the cover or index page. ''No, leave the Chicken version number on every manual page so that we know if a non-updated page exists. --John Cowan''
13'''Chicken is a compiler that translates Scheme source files into
14C''', which in turn can be fed to a C compiler to generate a
15standalone executable.  An interpreter is also available and can be
16used as a scripting environment or for testing programs before
19This chapter is designed to get you started with Chicken programming,
20describing what it is and what it will do for you, and covering basic
21use of the system. With almost everything discussed here, there is
22more to the story, which the remainder of the manual reveals. Here, we
23only cover enough to get you started. Nonetheless, someone who knows
24Scheme already should be able to use this chapter as the basis for
25writing and running small Chicken programs.
27=== Scheme
29Scheme is a member of the Lisp family of languages, of which Common
30Lisp and Emacs Lisp are the other two widely-known members. As with
31Lisp dialects, Scheme features
33* a wide variety of programming paradigms, including imperative, functional, and object-oriented
34* a very simple syntax, based upon nested parenthesization
35* the ability to extend the language in meaningful and useful ways
37In contrast to Common Lisp, Scheme is very minimal, and tries to
38include only those features absolutely necessary in programming. In
39contrast to Emacs Lisp, Scheme is not anchored into any one program
40(Emacs), and has a somewhat more modern language design.
42Scheme is defined in a document called ''The Revised<sup>5</sup> Report on the Algorithmic Language Scheme'', normally referred
43to as ``R5RS''. (Yes, it really has been revised five times, so an expanded version of its name would be ''The Revised Revised Revised Revised Revised Report''.)  A newer report, ``R6RS'' was
44released in 2007, but this report has attracted considerable
45controversy, and not all Scheme implementations will be made compliant
46with it. Chicken essentially complies with R5RS.
48Even though Scheme is consciously minimalist, it is recognized that a
49language must be more than a minimal core in order to be
50useful. Accordingly, the Scheme community uses a process known as
51`Scheme Requests For Implementation' (SRFI, pronounced `SUR-fee') to
52define new language features. A typical Scheme system therefore
53complies with one of the Scheme reports plus some or all of the
54accepted SRFIs.
56A good starting point for Scheme knowledge is
57[[]]. There you will find the defining reports,
58FAQs, lists of useful books and other resources, and the SRFIs.
60The Chicken community is at present developing tutorials for
61programmers who are new to Scheme but experienced with Python, Ruby,
62or other languages. These can be found on the Chicken wiki.
64=== Chicken
66Chicken is an implementation of Scheme that has many advantages.
69Chicken Scheme combines an optimising compiler with a reasonably fast
70interpreter.  It supports almost all of R5RS and the important SRFIs.
71The compiler generates portable C code that supports tail recursion,
72first-class continuations, and lightweight threads, and the interface to
73and from C libraries is flexible, efficient, and easy to use.  There are
74hundreds of contributed Chicken libraries that make the programmer's
75task easier.  The interpreter allows interactive use, fast prototyping,
76debugging, and scripting.  The active and helpful Chicken community
77fixes bugs and provides support.  Extensive documentation is supplied.
80Chicken includes
82* a Scheme interpreter that supports almost all of  R5RS Scheme, with
83  only a few relatively minor omissions, and with many extensions
84* a compatible compiler whose target is C, thus making porting to new
85  machines and architectures relatively straightforward
86** the C support allows Scheme code to include `embedded' C code,
87  thus making it relatively easy to invoke host OS or library
88  functions
89* a framework for language extensions, library modules that broaden
90  the functionality of the system
92This package is distributed under the '''BSD license''' and as such is free
93to use and modify.
95Scheme cognoscenti will appreciate the method of compilation and the
96design of the runtime-system, which follow closely Henry Baker's
97[[|CONS Should Not
98CONS Its Arguments, Part II: Cheney on the M.T.A.]] paper and expose a
99number of interesting properties.
101* Consing (creation of data on the heap) is relatively inexpensive,
102  because a generational garbage collection scheme is used, in which
103  short-lived data structures are reclaimed extremely quickly.
105* Moreover, {{call-with-current-continuation}} is practically for free
106  and Chicken does not suffer under any performance penalties if
107  first-class continuations are used in complex ways.
109The generated C code is fully tail-recursive.
111Some of the features supported by Chicken:
113* SRFIs 0, 1, 2, 4, 6-19, 23, 25-31, 37-40, 42, 43, 45, 47, 55, 57,
114  60-63, 66, 69, 72, 78, 85 and 95.
115* Lightweight threads based on first-class continuations
116* Pattern matching with Andrew Wright's {{match}} package
117* Record structures
118* Extended comment- and string-literal syntaxes
119* Libraries for regular expressions, string handling
120* UNIX system calls and extended data structures
121* Create interpreted or compiled shell scripts written in Scheme for
122  UNIX or Windows
123* Compiled C files can be easily distributed
124* Allows the creation of fully self-contained statically linked executables
125* On systems that support it, compiled code can be loaded dynamically
127Chicken has been used in many environments ranging from embedded
128systems through desktop machines to large-scale server deployments. 
129The number of language extensions, or '''eggs''', will soon reach 400,
132* extended language features
133* development tools, such as documentation generators, debugging, and
134  automated testing libraries
135* interfaces to other languages such as Java, Python, and Objective-C
136* interfaces to database systems, GUIs, and other large-scale
137  libraries,
138* network applications, such as servers and clients for ftp,
139  smtp/pop3, irc, and http 
140* web servers and related tools, including URL parsing, HTML
141  generation, AJAX, and HTTP session management
142* data formats, including XML, JSON, and Unicode support
144Chicken is supported by SWIG (Simplified Wrapper and Interface
145Generator), a tool that produces quick-and-dirty interface modules
146for C libraries ([[]]).
148This chapter provides you with an overview of the entire system, with
149enough information to get started writing and running small Scheme
150programs. Subsequent chapters cover
152* [[Basic mode of operation]]: Compiling Scheme files.
154* [[Using the compiler]]: Explains how to use Chicken to compile
155  programs and execute them.
157* [[Using the interpreter]]: Invocation and usage of {{csi}}, the
158  Chicken interpreter
160* [[Supported language]]: The language implemented by Chicken
161  (deviations from the standard and extensions).
163* [[Interface to external functions and variables]]: Accessing C and
164  C++ code and data.
166* [[chicken-setup]]: Packaging and installing extension libraries.
168* [[Data representation]]: How Scheme data is internally represented.
170* [[Bugs and limitations]]: Yes, there are some.
172* [[FAQ]]: A list of Frequently Asked Questions about Chicken (and
173  their answers!).
175* [[Acknowledgements]]: A list of some of the people that have
176  contributed to make Chicken what it is.
178* [[Bibliography]]: Links to documents that may be of interest.
180=== Installing Chicken
182Chicken is available in binary form for Windows and Linux/x86
183systems, and in source form for all other platforms. Refer to the
184{{README}} file in the distribution for instructions on installing it
185on your system.
187Because it compiles to C, Chicken requires that a C compiler be
188installed on your system. (If you're not writing embedded C code, you
189can pretty much ignore the C compiler once you have installed it.)
191* On a Linux system, the GNU Compiler Collection ({{gcc}}) should be installed as part of the basic operating system.
192* On Macintosh OS X, you will need the XCode tools, which are shipped on the OS X DVD with recent versions of the operating system.  ''What about Fink or such?''
193* On Windows, you have four choices.
194** Cygwin ([[]]) provides a relatively full-featured Unix environment for Windows.
195** The GNU Compiler Collection has been ported to Windows, in the MinGW system ([[]]). Unlike Cygwin,  executables produced with MinGW do not need the Cygwin DLLs in order to run.
196*** TODO: explain mingw build here
197*** TODO: explain mingw-msys build here
198** Microsoft Visual Studio will soon be supported, including the Express edition, which is a non-free but no-cost compiler suite available from Microsoft   ([[]]). Chicken supports command-line building using the Microsoft C/C++ compiler.  Visual Studio users will want to install the Unix Utilities, available at  [[]], in order to get suitable versions of {{make}}, {tar}}, {{gzip}}, and similar commands.
200TODO: what's the least we can possibly say about PATH,
201CHICKEN_INCLUDE_PATH, DYLD_LIBRARY_PATH, etc?  ''The least we can say at this point is nothing at all.  Let's do that.''
203=== Development environments
205The simplest development environment is a text editor and terminal
206window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm). If
207you install the {{readline}} egg (TODO: insert xref), you have all the
208benefits of command history and reentry, Emacs or vi-compatible line
209editing, and customization.
211You will need a text editor that knows Scheme; it's just too painful
212with editors that don't do parenthesis matching and proper
213indentation. Some editors allow you to execute Scheme code directly in
214the editor. This makes programming very interactive: you can type in a
215function and then try it right away. This feature is very highly
218As programmers have very specific tastes about editors, the editors
219listed here are shown in alphabetic order. We aren't about to tell you
220which editor to use, and there may be editors not shown here that
221might satisfy your needs.
223* Emacs ([[]]) is available for Linux/Unix, Macintosh, and Windows systems; CHICKEN provides Emacs support out of the box, with the {{hen.el}} Emacs Lisp file. Consult the ``Emacs Guide for Chicken Users'' (TODO: this document doesn't exist yet) for information on setting up and using Emacs with Chicken.
225* Epsilon ([[]]) is a commercial text editor whose design was   inspired by Emacs. Although Scheme support isn't provided,  a Lisp mode is available on Lugaru's FTP site, and could with some work be made to duplicate the Emacs support.
227* {{vim}} ([[]]) is a descendant of the venerable {{vi}} editor first included with Berkeley versions of Unix.  TODO: say more about using vim with Chicken, all I know about vi is that you can get out by typing :q! .
229TODO: other editors? Slick? Multi-Edit? Visual Studio? Eclipse? TextMate?  Please fill in anything you know about. Has somebody done a SchemeScript for Chicken?
231=== Using the interpreter
233In the rest of this chapter, we'll assume that you are using a
234terminal window.
236To invoke the interpreter, you use the {{csi}} command.
238 $ csi
240 (c)2000-2007 Felix L. Winkelmann
241 (c)2008 The Chicken Team
242 Version 3.0.1 - macosx-unix-gnu-x86    [ manyargs dload ptables applyhook ]
243 SVN rev. 8489  compiled 2008-02-15 on argyre.local (Darwin)
244 #;1>
246This brings up a brief banner, and then the prompt. You can use this
247pretty much like any other Scheme system, e.g.,
249 #;1> (define (twice f) (lambda (x) (f (f x))))
250 #;2> ((twice (lambda (n) (* n 10))) 3)
251 300
253Suppose  we have already created a file {{fact.scm}} containing a
254function definition.
256 (define (fact n)
257   (if (= n 0)
258       1
259       (* n (fact (- n 1)))))
261We can now load this file and try out the function.
263 #;3> (load "fact.scm")
264 ; loading fact.scm ...
265 #;4> (fact 3)
266 6
268The '''read-eval-print loop''' ('''REPL''') is the component of the
269Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
270and ''prints'' out the result. The REPL's prompt can be customized
271(TODO: xref),
272but the default prompt, showing the number of the form, is quite
275The REPL also supports debugging commands:
276input lines beginning with a {{,}} (comma) are treated as special
277commands. (TODO: insert cross-reference to full list) We can
278'''trace''' {{fact}} to see how it works.
280 #;5> ,tr fact
281 #;5> (fact 3)
282 |(fact 3)
283 | (fact 2)
284 |  (fact 1)
285 |   (fact 0)
286 |   fact -> 1
287 |  fact -> 1
288 | fact -> 2
289 |fact -> 6
290 6
292The command number didn't increment, because the {{tr}} command isn't
293actually a Scheme ''form''.
295==== Scripts
297You can use the interpreter to run a Scheme program from the command
298line. Here we create a program that does a quick search-and-replace on
299an input file; the arguments are a regular expression and a
300replacement string.
302 $ cat quickrep.dat
303 xyzabcghi
304 abxawxcgh
305 foonly
306 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
307 xyzAghi
308 Agh
309 foonly
311The {{-ss}} option sets several options that work smoothly together to
312execute a script. You can make the command directly executable from
313the shell by inserting a `shebang line' at the beginning of the
314program (TODO: insert xref).
316The program itself uses one of the libraries included with Chicken,
317the regular expression library, {{regex}}.
319 (use regex)
320 (define (process-line line re rplc)
321   (string-substitute re rplc line 'all))
322 (define (quickrep re rplc)
323   (let ((line (read-line)))
324     (if (not (eof-object? line))
325         (begin
326           (display (process-line line re rplc))
327           (newline)
328           (quickrep re rplc)))))
329 ;;; Does a lousy job of error checking!
330 (define (main args)
331   (quickrep (regexp (car args)) (cadr args)))
333The {{-ss}} option arranges to call a procedure named {{main}}, with
334the command line arguments, packed in a list, as its arguments. (There
335are a number of ways this program could be made more idiomatic Chicken
336Scheme, see the rest of the manual for details.)
338=== The compiler
340There are several reasons you might want to compile your code.
342* Compiled code executes substantially more quickly than interpreted
343  code.
344* You might want to deploy an application onto machines where the
345  users aren't expected to have Chicken installed: compiled
346  applications can be self-contained.
348The Chicken compiler is provided as the command {{chicken}}, but in
349almost all cases, you will want to use the {{csc}} command
350instead. {{csc}} is a convenient driver that automates compiling
351Scheme programs into C, compiling C code into object code, and linking
352the results into an executable file. (Note: in a Windows environment
353with Visual Studio, you may find that {{csc}} refers to Microsoft's
354C\# compiler. There are a number of ways of sorting this out, of which
355the simplest is to make a Windows batch file named {{cshc.bat}} which
356invokes the Chicken compiler, and organize your {{PATH}} accordingly.)
358Compiled code can be intermixed with interpreted code on systems that
359support dynamic loading, which includes modern versions of *BSD,
360Linux, Mac OS X, Solaris, and Windows.
362We can compile our factorial function, producing a file named
363{{}} (`shared object' in Linux-ese, the same file type is used
364in OS X and Windows).
366 chicken$ csc -dynamic fact.scm
367 chicken$ csi -quiet
368 #;1> (load "")
369 ; loading ...
370 #;2> (fact 6)
371 720
373On any system, we can just compile a program directly into an
374executable. Here's a program that tells you whether its argument is a
377 (define (palindrome? x)
378   (define (check left right)
379     (if (>= left right)
380         #t
381         (and (char=? (string-ref x left) (string-ref x right))
382              (check (add1 left) (sub1 right)))))
383   (check 0 (sub1 (string-length x))))
384 (let ((arg (car (command-line-arguments))))
385   (display
386    (string-append arg
387                   (if (palindrome? arg)
388                       " is a palindrome\n"
389                       " isn't a palindrome\n"))))
391We can compile this program using {{csc}}, creating an executable
392named {{palindrome}}.
394 $ csc -o palindrome palindrome.scm
395 $ ./palindrome level
396 level is a palindrome
397 $ ./palindrome liver
398 liver isn't a palindrome
400Chicken supports separate compilation, using some extensions to
401Scheme. Let's divide our palindrome program into a library module
402({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
404Here's the external library. We {{declare}} that {{pal-proc}} is a
405``unit'', which is the basis of separately-compiled modules in
406Chicken. (Units deal with separate compilation, but don't involve
407separated namespaces; namespaced module systems are available as
410 ;;; Library pal-proc.scm
411 (declare (unit pal-proc))
412 (define (palindrome? x)
413   (define (check left right)
414     (if (>= left right)
415         #t
416         (and (char=? (string-ref x left) (string-ref x right))
417              (check (add1 left) (sub1 right)))))
418   (check 0 (sub1 (string-length x))))
420Next we have some  client code that `uses' this separately-compiled
423 ;;; Client pal-user.scm
424 (declare (uses pal-proc))
425 (let ((arg (car (command-line-arguments))))
426   (display
427    (string-append arg
428                   (if (palindrome? arg)
429                       " is a palindrome\n"
430                       " isn't a palindrome\n"))))
432Now we can compile and link everything together. (We show the compile
433and link operations separately, but they can of course be combined
434into one command.)
436 $ csc -c pal-proc.scm
437 $ csc -c pal-user.scm
438 $ csc -o pal-separate pal-proc.o pal-user.o
439 $ ./pal-separate level
440 level is a palindrome
442=== Installing an egg
444Installing eggs is quite straightforward on systems that support
445dynamic loading (again, that would include *BSD, Linux, Mac OS X,
446Solaris, and Windows).  The command {{chicken-setup}} will fetch an
447egg from the master Chicken repository, and install it on your local
450In this example, we install the {{uri}} egg, for parsing Uniform
451Resource Identifiers. The installation produces a lot of output, which
452we have edited for space reasons.
454 $ chicken-setup uri
456 The extension uri does not exist.
457 Do you want to download it ? (yes/no/abort) [yes] yes
458 downloading uri.egg from ( eggs/3 80)
459   gzip -d -c ../uri.egg | tar xf -
460 .  /Users/vmanis/local/bin/csc -feature compiling-extension
461      -s -O2 -d1 uri.scm -o -check-imports -emit-exports uri.exports
462 ... (lots of stuff elided)
463 .  rm -fr /Users/vmanis/project/chicken/uri.egg
465First, {{chicken-setup}} asks us if we want to download the egg. It
466then uncompresses the egg, compiles the code, and installs the egg in
467the local Chicken repository.
469Now we can use our new egg.
471 #;1> (use uri)
472 ; loading /Users/vmanis/local/lib/chicken/3/ ...
473 ; loading /Users/vmanis/local/lib/chicken/3/ ...
474 ; loading /Users/vmanis/local/lib/chicken/3/ ...
475 ; loading /Users/vmanis/local/lib/chicken/3/ ...
476 ; loading /Users/vmanis/local/lib/chicken/3/ ...
477 ; loading /Users/vmanis/local/lib/chicken/3/ ...
478 #;2> (uri-host (uri ""))
479 ""
481=== Accessing C libraries
483Because Chicken compiles to C, and because a foreign function
484interface is built into the compiler, interfacing to a C library is
485quite straightforward. This means that nearly any facility available
486on the host system is accessible from Chicken, with more or less
489Let's create a simple C library, to demonstrate how this
490works. Here we have a function that will compute and return the '''n'''th
491Fibonacci number. (This isn't a particularly good use of C here,
492because we could write this function just as easily in Scheme, but a
493real example would take far too much space here.)
495 int fib(int n) {
496   int prev = 0, curr = 1;
497   int next;
498   int i;
499   for (i = 0; i < n; i++) {
500     next = prev + curr;
501     prev = curr;
502     curr = next;
503   }
504   return curr;
505 }
507Now we can call this function from Chicken.
509 #>
510   extern fib(int n);
511 <#
512 (define xfib (foreign-lambda int "fib" int))
513 (do ((i 0 (+ i 1))) ((> i 10))
514   (printf "~A " (xfib i)))
515 (newline)
517The syntax {{#>...<#}} allows you to include literal C (typically
518external declarations) in your Chicken code. We access {{fib}} by
519defining a {{foreign-lambda}} for it, in this case saying that the
520function takes one integer argument (the {{int}} after the function
521name), and that it returns an integer result. Now we can invoke
522{{xfib}} as though it were an ordinary Scheme function.
524 $ gcc -c fib.c
525 $ csc -o fib-user fib.o fib-user.scm
526 $ ./fib-user
527 0 1 1 2 3 5 8 13 21 34 55
529Those who are interfacing to substantial C libraries should consider using the
530easyffi egg, or SWIG.
Note: See TracBrowser for help on using the repository browser.