source: project/wiki/man/4/Getting started @ 15309

Last change on this file since 15309 was 15309, checked in by felix winkelmann, 12 years ago

A few manual and wiki fixes, thanks to Sam Varner

File size: 24.6 KB
1[[tags: manual]]
3== Getting started
5Chicken is a compiler that translates Scheme source files into
6C, which in turn can be fed to a C compiler to generate a
7standalone executable.  An interpreter is also available and can be
8used as a scripting environment or for testing programs before
11This chapter is designed to get you started with Chicken programming,
12describing what it is and what it will do for you, and covering basic
13use of the system. With almost everything discussed here, there is
14more to the story, which the remainder of the manual reveals. Here, we
15only cover enough to get you started. Nonetheless, someone who knows
16Scheme already should be able to use this chapter as the basis for
17writing and running small Chicken programs.
19=== Scheme
21Scheme is a member of the Lisp family of languages, of which Common
22Lisp and Emacs Lisp are the other two widely-known members. As with
23Lisp dialects, Scheme features
25* a wide variety of programming paradigms, including imperative, functional, and object-oriented
26* a very simple syntax, based upon nested parenthesization
27* the ability to extend the language in meaningful and useful ways
29In contrast to Common Lisp, Scheme is very minimal, and tries to
30include only those features absolutely necessary in programming. In
31contrast to Emacs Lisp, Scheme is not anchored into any one program
32(Emacs), and has a somewhat more modern language design.
34Scheme is defined in a document called ''The Revised^5 Report on the
35Algorithmic Language Scheme'', or ''R5RS'' for short. (Yes, it really
36has been revised five times, so an expanded version of its name would
37be ''The Revised Revised Revised Revised Revised Report''.)  A newer
38report, ''R6RS'', was
39released in 2007, but this report has attracted considerable
40controversy, and not all Scheme implementations will be made compliant
41with it. Chicken essentially complies with R5RS.
43Even though Scheme is consciously minimalist, it is recognized that a
44language must be more than a minimal core in order to be
45useful. Accordingly, the Scheme community uses a process known as
46`Scheme Requests For Implementation' (SRFI, pronounced `SUR-fee') to
47define new language features. A typical Scheme system therefore
48complies with one of the Scheme reports plus some or all of the
49accepted SRFIs.
51A good starting point for Scheme knowledge is
52[[]]. There you will find the defining reports,
53FAQs, lists of useful books and other resources, and the SRFIs.
55The Chicken community is at present developing tutorials for
56programmers who are new to Scheme but experienced with Python, Ruby,
57or other languages. These can be found on the Chicken wiki.
59=== Chicken
61Chicken is an implementation of Scheme that has many advantages.
64Chicken Scheme combines an optimising compiler with a reasonably fast
65interpreter.  It supports almost all of R5RS and the important SRFIs.
66The compiler generates portable C code that supports tail recursion,
67first-class continuations, and lightweight threads, and the interface to
68and from C libraries is flexible, efficient, and easy to use.  There are
69hundreds of contributed Chicken libraries that make the programmer's
70task easier.  The interpreter allows interactive use, fast prototyping,
71debugging, and scripting.  The active and helpful Chicken community
72fixes bugs and provides support.  Extensive documentation is supplied.
75Chicken was developed by Felix L. Winkelmann over the period from 2000
76through 2007. In early 2008, Felix
77asked the community to take over the responsibility of developing and
78maintaining the system, though he still takes a strong interest in it,
79and participates actively.
81Chicken includes
83* a Scheme interpreter that supports almost all of  R5RS Scheme, with
84  only a few relatively minor omissions, and with many extensions
85* a compatible compiler whose target is C, thus making porting to new
86  machines and architectures relatively straightforward
87** the C support allows Scheme code to include `embedded' C code,
88  thus making it relatively easy to invoke host OS or library
89  functions
90* a framework for language extensions, library modules that broaden
91  the functionality of the system
93This package is distributed under the '''BSD license''' and as such is free
94to use and modify.
96Scheme cognoscenti will appreciate the method of compilation and the
97design of the runtime-system, which follow closely Henry Baker's
98[[|CONS Should Not
99CONS Its Arguments, Part II: Cheney on the M.T.A.]] paper and expose a
100number of interesting properties.
102* Consing (creation of data on the heap) is relatively inexpensive,
103  because a generational garbage collection scheme is used, in which
104  short-lived data structures are reclaimed extremely quickly.
106* Moreover, {{call-with-current-continuation}} is practically for free
107  and Chicken does not suffer under any performance penalties if
108  first-class continuations are used in complex ways.
110The generated C code is fully tail-recursive.
112Some of the features supported by Chicken:
114* SRFIs 0, 1, 2, 4, 6-19, 23, 25-31, 37-40, 42, 43, 45, 47, 55, 57,
115  60-63, 66, 69, 72, 78, 85, 95 and 98.
116* Lightweight threads based on first-class continuations
117* Pattern matching with Andrew Wright's {{match}} package
118* Record structures
119* Extended comment- and string-literal syntaxes
120* Libraries for regular expressions, string handling
121* UNIX system calls and extended data structures
122* Create interpreted or compiled shell scripts written in Scheme for
123  UNIX or Windows
124* Compiled C files can be easily distributed
125* Allows the creation of fully self-contained statically linked executables
126* On systems that support it, compiled code can be loaded dynamically
128Chicken has been used in many environments ranging from embedded
129systems through desktop machines to large-scale server deployments. 
130The number of language extensions, or '''eggs''', is constantly growing.
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* [[Extensions]]: 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=== Chicken repositories, websites, and community
182At present, the URLs for Chicken information and download are somewhat
183confusing. It is envisaged that everything will eventually be
184accessible via the
185domain {{}}, but this hasn't been completely done.
187At present, the master Chicken website is
188[[]]. Here you can find
189basic information about Chicken, downloads, and pointers to other key
192The Chicken wiki ([[]]) contains the most
193current version of the User's manual, along with various tutorials and
194other useful documents. The list of eggs is at
197A very useful search facility for questions about Chicken is found at
198[[]]. The Chicken issue tracker is at
201The Chicken community has two major mailing lists. If you are a
202Chicken user, {{Chicken-Users}}
203([[]]) will be
204of interest. The crew working on the Chicken system itself uses the
205very low-volume {{Chicken-Hackers}} list
206([[]]) for
209=== Installing Chicken
211Chicken is available in binary form for Windows and Linux/x86
212systems, and in source form for all other platforms. Refer to the
213{{README}} file in the distribution for instructions on installing it
214on your system.
216Because it compiles to C, Chicken requires that a C compiler be
217installed on your system. (If you're not writing embedded C code, you
218can pretty much ignore the C compiler once you have installed it.)
220* On a Linux system, the GNU Compiler Collection ({{gcc}}) should be
221  installed as part of the basic operating system, or should be
222  available through the package management system (e.g., APT,
223  Synaptic, RPM, or Yum, depending upon your Linux distribution).
224* On Macintosh OS X, you will need the XCode tools, which are shipped
225  on the OS X DVD with recent versions of the operating system.
226* On Windows, you have three choices.
227** Cygwin ([[]]) provides a relatively
228  full-featured Unix environment for Windows.  Chicken works
229  substantially the same in Cygwin and Unix.
230** The GNU Compiler Collection has been ported to Windows, in the
231  MinGW system ([[]]). Unlike Cygwin,
232  executables produced with MinGW do not need the Cygwin DLLs in order
233  to run.   MSys is a companion package to MinGW; it provides a minimum
234  Unix-style development/build environment, again ported from free
235  software.
236*** You can build Chicken either with MinGW alone or with MinGW plus
237  MSys. Both approaches produce a Chicken built against the mingw headers
238  and import libraries.
239  The only difference is the environment where you actually run make.
240  {{Makefile.mingw}} is can be used in {{cmd.exe}} with the version of make
241  that comes with mingw.  {{Makefile.mingw-msys}}
242  uses unix commands such as {{cp}} and {{rm}}.  The end product is the
243  same.
244** Microsoft Visual Studio will soon be supported, including the
245  Express edition, which is a non-free but no-cost compiler suite
246  available from Microsoft
247  ([[]]). Chicken supports
248  command-line building using the command-line C/C++ compiler.
249*** Visual
250  Studio users will want to install the Unix Utilities, available at
251  [[]],
252  in order to get suitable versions of {{make}}, {{tar}}, {{gzip}}, and
253  similar commands. 
255Refer to the {{README}} file for the version you're installing for
256more information on the installation process.
258=== Development environments
260The simplest development environment is a text editor and terminal
261window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for
262using the interpreter and/or calling the compiler. If you
263[[/egg/readline|install the {{readline}} egg]], you
264have all the benefits of command history in the interpreter, Emacs or
265vi-compatible line editing, and customization.
267You will need a text editor that knows Scheme; it's just too painful
268with editors that don't do parenthesis matching and proper
269indentation. Some editors allow you to execute Scheme code directly in
270the editor. This makes programming very interactive: you can type in a
271function and then try it right away. This feature is very highly
274As programmers have very specific tastes about editors, the editors
275listed here are shown in alphabetic order. We aren't about to tell you
276which editor to use, and there may be editors not shown here that
277might satisfy your needs. We would be very interested in reports of
278other editors that have been used with Chicken, especially those that
279support interactive evaluation of forms during editing. Pointers to
280these (and to any editor customization files appropriate) should be
281put on the Chicken wiki, and will likely be added to future editions
282of this manual. (We have had a request for editors that support
283proportional fonts, in particular.)
285* Emacs ([[]]) is an
286extensible, customizable, self-documenting editor available for
287Linux/Unix, Macintosh, and Windows systems; CHICKEN provides Emacs
288support out of the box, with the {{hen.el}} Emacs Lisp file. Consult
289the `Emacs Guide for Chicken Users' (which will be available on the
290Chicken Wiki soon) for information on setting up and using Emacs with
293* Epsilon ([[]]) is a commercial (proprietary) text
294editor whose design was inspired by Emacs. Although Scheme support
295isn't provided, a Lisp mode is available on Lugaru's FTP site, and
296could with some work be made to duplicate the Emacs support. 
298* SciTE ([[]]),
299unlike Emacs or Vim, follows typical graphical UI design conventions
300and control-key mappings, and for simple tasks is as familiar and
301easy to use as Notepad, KEdit, TeachText etc.  However it has many
302programming features such as multiple open files, syntax
303highlighting for a large number of languages (including Lisps),
304matching of brackets, ability to fold sections of code based on the
305matched brackets, column selections, comment/uncomment, and the
306ability to run commands in the same directory as the current file
307(such as make, grep, etc.)  SciTE is written with the GTK toolkit
308and is portable to any GTK platform, including Windows, Linux and
309MacOS.  It uses the Scintilla text-editing component, which lends
310itself well to embedding within other IDEs and graphical toolkits.
311It does not have any other Scheme-specific features, but being
312open-source and modular, features like auto-formatting of
313S-expressions could be added.  The syntax highlighting can be
314configured to use different fonts for different types of syntax,
315including proportional fonts.
317* Vim ([[]]) is a highly configurable text
318editor built to enable efficient and fast text editing. It is an
319improved version of the vi editor distributed with most UNIX
320systems. Vim comes with generic Lisp (and therefore Scheme) editing
321capabilities out of the
322box. A few tips on using Vim with Chicken can be found at
325In the rest of this chapter, we'll assume that you are using an editor
326of your choice and a regular terminal window for executing your
327Chicken code.
329=== The Read-Eval-Print loop
331To invoke the Chicken interpreter, you use the {{csi}} command.
333 $ csi
335 (c)2008 The Chicken Team
336 (c)2000-2007 Felix L. Winkelmann
337 Version 3.1.2 - macosx-unix-gnu-x86    [ manyargs dload ptables applyhook ]
338 SVN rev. 10185 compiled 2008-03-27 on argyre.local (Darwin)
339 #;1>
341This brings up a brief banner, and then the prompt. You can use this
342pretty much like any other Scheme system, e.g.,
344 #;1> (define (twice f) (lambda (x) (f (f x))))
345 #;2> ((twice (lambda (n) (* n 10))) 3)
346 300
348Suppose  we have already created a file {{fact.scm}} containing a
349function definition.
351 (define (fact n)
352   (if (= n 0)
353       1
354       (* n (fact (- n 1)))))
356We can now load this file and try out the function.
358 #;3> (load "fact.scm")
359 ; loading fact.scm ...
360 #;4> (fact 3)
361 6
363The '''read-eval-print loop''' ('''REPL''') is the component of the
364Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
365and ''prints'' out the result. The REPL's prompt can be customized
366(see the [[http:Using%20the%20interpreter|`Using the Interpreter']])
367but the default prompt, showing the number of the form, is quite
370The REPL also supports debugging commands:
371input lines beginning with a {{,}} (comma) are treated as special
372commands. (See the [[Using the interpreter#Toplevel commands|full list]].) We can
373'''trace''' {{fact}} to see how it works.
375 #;5> ,tr fact
376 #;5> (fact 3)
377 |(fact 3)
378 | (fact 2)
379 |  (fact 1)
380 |   (fact 0)
381 |   fact -> 1
382 |  fact -> 1
383 | fact -> 2
384 |fact -> 6
385 6
387The command number didn't increment, because the {{tr}} command isn't
388actually a Scheme ''form''.
390==== Scripts
392You can use the interpreter to run a Scheme program from the command
393line. Here we create a program that does a quick search-and-replace on
394an input file; the arguments are a regular expression and a
395replacement string.
397 $ cat quickrep.dat
398 xyzabcghi
399 abxawxcgh
400 foonly
401 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
402 xyzAghi
403 Agh
404 foonly
406The {{-ss}} option sets several options that work smoothly together to
407execute a script. You can make the command directly executable from
408the shell by inserting a `[[Using the interpreter#Writing Scheme scripts|shebang line]]' at the beginning of the
411{{regex}}, the regular expression library, is one of the libraries
412included with Chicken.
414 (use regex)
415 (define (process-line line re rplc)
416   (string-substitute re rplc line 'all))
417 (define (quickrep re rplc)
418   (let ((line (read-line)))
419     (if (not (eof-object? line))
420         (begin
421           (display (process-line line re rplc))
422           (newline)
423           (quickrep re rplc)))))
424 ;;; Does a lousy job of error checking!
425 (define (main args)
426   (quickrep (regexp (car args)) (cadr args)))
428The {{-ss}} option arranges to call a procedure named {{main}}, with
429the command line arguments, packed in a list, as its arguments. (There
430are a number of ways this program could be made more idiomatic Chicken
431Scheme, see the rest of the manual for details.)
433=== The compiler
435There are several reasons you might want to compile your code.
437* Compiled code executes substantially faster than interpreted
438  code.
439* You might want to deploy an application onto machines where the
440  users aren't expected to have Chicken installed: compiled
441  applications can be self-contained.
443The Chicken compiler is provided as the command {{chicken}}, but in
444almost all cases, you will want to use the {{csc}} command
445instead. {{csc}} is a convenient driver that automates compiling
446Scheme programs into C, compiling C code into object code, and linking
447the results into an executable file. (Note: in a Windows environment
448with Visual Studio, you may find that {{csc}} refers to Microsoft's
449C# compiler. There are a number of ways of sorting this out, of which
450the simplest is to rename one of the two tools, and/or to
451organize your {{PATH}} according to the task at hand.)
453Compiled code can be intermixed with interpreted code on systems that
454support dynamic loading, which includes modern versions of *BSD,
455Linux, Mac OS X, Solaris, and Windows.
457We can compile our factorial function, producing a file named
458{{}} (`shared object' in Linux-ese, the same file type is used
459in OS X and Windows, rather than {{dylib}} or {{dll}}, respectively).
461 chicken$ csc -dynamic fact.scm
462 chicken$ csi -quiet
463 #;1> (load "")
464 ; loading ...
465 #;2> (fact 6)
466 720
468On any system, we can just compile a program directly into an
469executable. Here's a program that tells you whether its argument is a
472 (define (palindrome? x)
473   (define (check left right)
474     (if (>= left right)
475         #t
476         (and (char=? (string-ref x left) (string-ref x right))
477              (check (add1 left) (sub1 right)))))
478   (check 0 (sub1 (string-length x))))
479 (let ((arg (car (command-line-arguments))))
480   (display
481    (string-append arg
482                   (if (palindrome? arg)
483                       " is a palindrome\n"
484                       " isn't a palindrome\n"))))
486We can compile this program using {{csc}}, creating an executable
487named {{palindrome}}.
489 $ csc -o palindrome palindrome.scm
490 $ ./palindrome level
491 level is a palindrome
492 $ ./palindrome liver
493 liver isn't a palindrome
495Chicken supports separate compilation, using some extensions to
496Scheme. Let's divide our palindrome program into a library module
497({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
499Here's the external library. We {{declare}} that {{pal-proc}} is a
500`unit', which is the basis of separately-compiled modules in
501Chicken. (Units deal with separate compilation, but don't involve
502separated namespaces; namespaced module systems are available as
505 ;;; Library pal-proc.scm
506 (declare (unit pal-proc))
507 (define (palindrome? x)
508   (define (check left right)
509     (if (>= left right)
510         #t
511         (and (char=? (string-ref x left) (string-ref x right))
512              (check (add1 left) (sub1 right)))))
513   (check 0 (sub1 (string-length x))))
515Next we have some  client code that `uses' this separately-compiled
518 ;;; Client pal-user.scm
519 (declare (uses pal-proc))
520 (let ((arg (car (command-line-arguments))))
521   (display
522    (string-append arg
523                   (if (palindrome? arg)
524                       " is a palindrome\n"
525                       " isn't a palindrome\n"))))
527Now we can compile and link everything together. (We show the compile
528and link operations separately, but they can of course be combined
529into one command.)
531 $ csc -c pal-proc.scm
532 $ csc -c pal-user.scm
533 $ csc -o pal-separate pal-proc.o pal-user.o
534 $ ./pal-separate level
535 level is a palindrome
537=== Installing an egg
539Installing eggs is quite straightforward on systems that support
540dynamic loading (again, that would include *BSD, Linux, Mac OS X,
541Solaris, and Windows).  The command {{chicken-install}} will fetch an
542egg from the master Chicken repository, and install it on your local
545In this example, we install the {{uri}} egg, for parsing Uniform
546Resource Identifiers. The installation produces a lot of output, which
547we have edited for space reasons.
549 $ chicken-install uri
551 The extension uri does not exist.
552 Do you want to download it ? (yes/no/abort) [yes] yes
553 downloading uri.egg from ( eggs/3 80)
554   gzip -d -c ../uri.egg | tar xf -
555 .  /Users/vmanis/local/bin/csc -feature compiling-extension
556      -s -O2 -d1 uri.scm -o -check-imports -emit-exports uri.exports
557 ... (lots of stuff elided)
558 .  rm -fr /Users/vmanis/project/chicken/uri.egg
560First, {{chicken-install}} asks us if we want to download the egg. It
561then uncompresses the egg, compiles the code, and installs the egg in
562the local Chicken repository.
564Now we can use our new egg.
566 #;1> (use uri)
567 ; loading /Users/vmanis/local/lib/chicken/3/ ...
568 ; loading /Users/vmanis/local/lib/chicken/3/ ...
569 ; loading /Users/vmanis/local/lib/chicken/3/ ...
570 ; loading /Users/vmanis/local/lib/chicken/3/ ...
571 ; loading /Users/vmanis/local/lib/chicken/3/ ...
572 ; loading /Users/vmanis/local/lib/chicken/3/ ...
573 #;2> (uri-host (uri ""))
574 ""
576=== Accessing C libraries
578Because Chicken compiles to C, and because a foreign function
579interface is built into the compiler, interfacing to a C library is
580quite straightforward. This means that nearly any facility available
581on the host system is accessible from Chicken, with more or less
584Let's create a simple C library, to demonstrate how this
585works. Here we have a function that will compute and return the '''n'''th
586Fibonacci number. (This isn't a particularly good use of C here,
587because we could write this function just as easily in Scheme, but a
588real example would take far too much space here.)
590 /* fib.c */
591 int fib(int n) {
592   int prev = 0, curr = 1;
593   int next;
594   int i;
595   for (i = 0; i < n; i++) {
596     next = prev + curr;
597     prev = curr;
598     curr = next;
599   }
600   return curr;
601 }
603Now we can call this function from Chicken.
605 ;;; fib-user.scm
606 #>
607   extern int fib(int n);
608 <#
609 (define xfib (foreign-lambda int "fib" int))
610 (do ((i 0 (+ i 1))) ((> i 10))
611   (printf "~A " (xfib i)))
612 (newline)
614The syntax {{#>...<#}} allows you to include literal C (typically
615external declarations) in your Chicken code. We access {{fib}} by
616defining a {{foreign-lambda}} for it, in this case saying that the
617function takes one integer argument (the {{int}} after the function
618name), and that it returns an integer result (the {{int}} before.) Now we can invoke
619{{xfib}} as though it were an ordinary Scheme function.
621 $ gcc -c fib.c
622 $ csc -o fib-user fib.o fib-user.scm
623 $ ./fib-user
624 0 1 1 2 3 5 8 13 21 34 55
626Those who are interfacing to substantial C libraries should consider
627using the [[easyffi]] egg.
631Back to [[The User's Manual]]
633Next: [[Basic mode of operation]]
Note: See TracBrowser for help on using the repository browser.