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

Last change on this file since 14114 was 14114, checked in by sjamaan, 12 years ago

Change chicken-setup reference to chicken-install

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 and 95.
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''', will soon reach 400,
133* extended language features
134* development tools, such as documentation generators, debugging, and
135  automated testing libraries
136* interfaces to other languages such as Java, Python, and Objective-C
137* interfaces to database systems, GUIs, and other large-scale
138  libraries,
139* network applications, such as servers and clients for ftp,
140  smtp/pop3, irc, and http 
141* web servers and related tools, including URL parsing, HTML
142  generation, AJAX, and HTTP session management
143* data formats, including XML, JSON, and Unicode support
145Chicken is supported by SWIG (Simplified Wrapper and Interface
146Generator), a tool that produces quick-and-dirty interface modules
147for C libraries ([[]]).
149This chapter provides you with an overview of the entire system, with
150enough information to get started writing and running small Scheme
151programs. Subsequent chapters cover
153* [[Basic mode of operation]]: Compiling Scheme files.
155* [[Using the compiler]]: Explains how to use Chicken to compile
156  programs and execute them.
158* [[Using the interpreter]]: Invocation and usage of {{csi}}, the
159  Chicken interpreter
161* [[Supported language]]: The language implemented by Chicken
162  (deviations from the standard and extensions).
164* [[Interface to external functions and variables]]: Accessing C and
165  C++ code and data.
167* [[Extensions]]: Packaging and installing extension libraries.
169* [[Data representation]]: How Scheme data is internally represented.
171* [[Bugs and limitations]]: Yes, there are some.
173* [[FAQ]]: A list of Frequently Asked Questions about Chicken (and
174  their answers!).
176* [[Acknowledgements]]: A list of some of the people that have
177  contributed to make Chicken what it is.
179* [[Bibliography]]: Links to documents that may be of interest.
181=== Chicken repositories, websites, and community
183At present, the URLs for Chicken information and download are somewhat
184confusing. It is envisaged that everything will eventually be
185accessible via the
186domain {{}}, but this hasn't been completely done.
188At present, the master Chicken website is
189[[]]. Here you can find
190basic information about Chicken, downloads, and pointers to other key
193The Chicken wiki ([[]]) contains the most
194current version of the User's manual, along with various tutorials and
195other useful documents. The list of eggs is at
198A very useful search facility for questions about Chicken is found at
199[[]]. The Chicken issue tracker is at
202The Chicken community has two major mailing lists. If you are a
203Chicken user, {{Chicken-Users}}
204([[]]) will be
205of interest. The crew working on the Chicken system itself uses the
206very low-volume {{Chicken-Hackers}} list
207([[]]) for
210=== Installing Chicken
212Chicken is available in binary form for Windows and Linux/x86
213systems, and in source form for all other platforms. Refer to the
214{{README}} file in the distribution for instructions on installing it
215on your system.
217Because it compiles to C, Chicken requires that a C compiler be
218installed on your system. (If you're not writing embedded C code, you
219can pretty much ignore the C compiler once you have installed it.)
221* On a Linux system, the GNU Compiler Collection ({{gcc}}) should be
222  installed as part of the basic operating system, or should be
223  available through the package management system (e.g., APT,
224  Synaptic, RPM, or Yum, depending upon your Linux distribution).
225* On Macintosh OS X, you will need the XCode tools, which are shipped
226  on the OS X DVD with recent versions of the operating system.
227* On Windows, you have three choices.
228** Cygwin ([[]]) provides a relatively
229  full-featured Unix environment for Windows.  Chicken works
230  substantially the same in Cygwin and Unix.
231** The GNU Compiler Collection has been ported to Windows, in the
232  MinGW system ([[]]). Unlike Cygwin,
233  executables produced with MinGW do not need the Cygwin DLLs in order
234  to run.   MSys is a companion package to MinGW; it provides a minimum
235  Unix-style development/build environment, again ported from free
236  software.
237*** You can build Chicken either with MinGW alone or with MinGW plus
238  MSys. Both approaches produce a Chicken built against the mingw headers
239  and import libraries.
240  The only difference is the environment where you actually run make.
241  {{Makefile.mingw}} is can be used in {{cmd.exe}} with the version of make
242  that comes with mingw.  {{Makefile.mingw-msys}}
243  uses unix commands such as {{cp}} and {{rm}}.  The end product is the
244  same.
245** Microsoft Visual Studio will soon be supported, including the
246  Express edition, which is a non-free but no-cost compiler suite
247  available from Microsoft
248  ([[]]). Chicken supports
249  command-line building using the command-line C/C++ compiler.
250*** Visual
251  Studio users will want to install the Unix Utilities, available at
252  [[]],
253  in order to get suitable versions of {{make}}, {{tar}}, {{gzip}}, and
254  similar commands. 
256Refer to the {{README}} file for the version you're installing for
257more information on the installation process.
259=== Development environments
261The simplest development environment is a text editor and terminal
262window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for
263using the interpreter and/or calling the compiler. If you
264[[/egg/readline|install the {{readline}} egg]], you
265have all the benefits of command history in the interpreter, Emacs or
266vi-compatible line editing, and customization.
268You will need a text editor that knows Scheme; it's just too painful
269with editors that don't do parenthesis matching and proper
270indentation. Some editors allow you to execute Scheme code directly in
271the editor. This makes programming very interactive: you can type in a
272function and then try it right away. This feature is very highly
275As programmers have very specific tastes about editors, the editors
276listed here are shown in alphabetic order. We aren't about to tell you
277which editor to use, and there may be editors not shown here that
278might satisfy your needs. We would be very interested in reports of
279other editors that have been used with Chicken, especially those that
280support interactive evaluation of forms during editing. Pointers to
281these (and to any editor customization files appropriate) should be
282put on the Chicken wiki, and will likely be added to future editions
283of this manual. (We have had a request for editors that support
284proportional fonts, in particular.)
286* Emacs ([[]]) is an
287extensible, customizable, self-documenting editor available for
288Linux/Unix, Macintosh, and Windows systems; CHICKEN provides Emacs
289support out of the box, with the {{hen.el}} Emacs Lisp file. Consult
290the `Emacs Guide for Chicken Users' (which will be available on the
291Chicken Wiki soon) for information on setting up and using Emacs with
294* Epsilon ([[]]) is a commercial (proprietary) text
295editor whose design was inspired by Emacs. Although Scheme support
296isn't provided, a Lisp mode is available on Lugaru's FTP site, and
297could with some work be made to duplicate the Emacs support. 
299* SciTE ([[]]),
300unlike Emacs or Vim, follows typical graphical UI design conventions
301and control-key mappings, and for simple tasks is as familiar and
302easy to use as Notepad, KEdit, TeachText etc.  However it has many
303programming features such as multiple open files, syntax
304highlighting for a large number of languages (including Lisps),
305matching of brackets, ability to fold sections of code based on the
306matched brackets, column selections, comment/uncomment, and the
307ability to run commands in the same directory as the current file
308(such as make, grep, etc.)  SciTE is written with the GTK toolkit
309and is portable to any GTK platform, including Windows, Linux and
310MacOS.  It uses the Scintilla text-editing component, which lends
311itself well to embedding within other IDEs and graphical toolkits.
312It does not have any other Scheme-specific features, but being
313open-source and modular, features like auto-formatting of
314S-expressions could be added.  The syntax highlighting can be
315configured to use different fonts for different types of syntax,
316including proportional fonts.
318* Vim ([[]]) is a highly configurable text
319editor built to enable efficient and fast text editing. It is an
320improved version of the vi editor distributed with most UNIX
321systems. Vim comes with generic Lisp (and therefore Scheme) editing
322capabilities out of the
323box. A few tips on using Vim with Chicken can be found at
326In the rest of this chapter, we'll assume that you are using an editor
327of your choice and a regular terminal window for executing your
328Chicken code.
330=== The Read-Eval-Print loop
332To invoke the Chicken interpreter, you use the {{csi}} command.
334 $ csi
336 (c)2008 The Chicken Team
337 (c)2000-2007 Felix L. Winkelmann
338 Version 3.1.2 - macosx-unix-gnu-x86    [ manyargs dload ptables applyhook ]
339 SVN rev. 10185 compiled 2008-03-27 on argyre.local (Darwin)
340 #;1>
342This brings up a brief banner, and then the prompt. You can use this
343pretty much like any other Scheme system, e.g.,
345 #;1> (define (twice f) (lambda (x) (f (f x))))
346 #;2> ((twice (lambda (n) (* n 10))) 3)
347 300
349Suppose  we have already created a file {{fact.scm}} containing a
350function definition.
352 (define (fact n)
353   (if (= n 0)
354       1
355       (* n (fact (- n 1)))))
357We can now load this file and try out the function.
359 #;3> (load "fact.scm")
360 ; loading fact.scm ...
361 #;4> (fact 3)
362 6
364The '''read-eval-print loop''' ('''REPL''') is the component of the
365Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
366and ''prints'' out the result. The REPL's prompt can be customized
367(see the [[http:Using%20the%20interpreter|`Using the Interpreter']])
368but the default prompt, showing the number of the form, is quite
371The REPL also supports debugging commands:
372input lines beginning with a {{,}} (comma) are treated as special
373commands. (See the [[Using the interpreter#Toplevel commands|full list]].) We can
374'''trace''' {{fact}} to see how it works.
376 #;5> ,tr fact
377 #;5> (fact 3)
378 |(fact 3)
379 | (fact 2)
380 |  (fact 1)
381 |   (fact 0)
382 |   fact -> 1
383 |  fact -> 1
384 | fact -> 2
385 |fact -> 6
386 6
388The command number didn't increment, because the {{tr}} command isn't
389actually a Scheme ''form''.
391==== Scripts
393You can use the interpreter to run a Scheme program from the command
394line. Here we create a program that does a quick search-and-replace on
395an input file; the arguments are a regular expression and a
396replacement string.
398 $ cat quickrep.dat
399 xyzabcghi
400 abxawxcgh
401 foonly
402 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
403 xyzAghi
404 Agh
405 foonly
407The {{-ss}} option sets several options that work smoothly together to
408execute a script. You can make the command directly executable from
409the shell by inserting a `[[Using the interpreter#Writing Scheme scripts|shebang line]]' at the beginning of the
412{{regex}}, the regular expression library, is one of the libraries
413included with Chicken.
415 (use regex)
416 (define (process-line line re rplc)
417   (string-substitute re rplc line 'all))
418 (define (quickrep re rplc)
419   (let ((line (read-line)))
420     (if (not (eof-object? line))
421         (begin
422           (display (process-line line re rplc))
423           (newline)
424           (quickrep re rplc)))))
425 ;;; Does a lousy job of error checking!
426 (define (main args)
427   (quickrep (regexp (car args)) (cadr args)))
429The {{-ss}} option arranges to call a procedure named {{main}}, with
430the command line arguments, packed in a list, as its arguments. (There
431are a number of ways this program could be made more idiomatic Chicken
432Scheme, see the rest of the manual for details.)
434=== The compiler
436There are several reasons you might want to compile your code.
438* Compiled code executes substantially faster than interpreted
439  code.
440* You might want to deploy an application onto machines where the
441  users aren't expected to have Chicken installed: compiled
442  applications can be self-contained.
444The Chicken compiler is provided as the command {{chicken}}, but in
445almost all cases, you will want to use the {{csc}} command
446instead. {{csc}} is a convenient driver that automates compiling
447Scheme programs into C, compiling C code into object code, and linking
448the results into an executable file. (Note: in a Windows environment
449with Visual Studio, you may find that {{csc}} refers to Microsoft's
450C# compiler. There are a number of ways of sorting this out, of which
451the simplest is to rename one of the two tools, and/or to
452organize your {{PATH}} according to the task at hand.)
454Compiled code can be intermixed with interpreted code on systems that
455support dynamic loading, which includes modern versions of *BSD,
456Linux, Mac OS X, Solaris, and Windows.
458We can compile our factorial function, producing a file named
459{{}} (`shared object' in Linux-ese, the same file type is used
460in OS X and Windows, rather than {{dylib}} or {{dll}}, respectively).
462 chicken$ csc -dynamic fact.scm
463 chicken$ csi -quiet
464 #;1> (load "")
465 ; loading ...
466 #;2> (fact 6)
467 720
469On any system, we can just compile a program directly into an
470executable. Here's a program that tells you whether its argument is a
473 (define (palindrome? x)
474   (define (check left right)
475     (if (>= left right)
476         #t
477         (and (char=? (string-ref x left) (string-ref x right))
478              (check (add1 left) (sub1 right)))))
479   (check 0 (sub1 (string-length x))))
480 (let ((arg (car (command-line-arguments))))
481   (display
482    (string-append arg
483                   (if (palindrome? arg)
484                       " is a palindrome\n"
485                       " isn't a palindrome\n"))))
487We can compile this program using {{csc}}, creating an executable
488named {{palindrome}}.
490 $ csc -o palindrome palindrome.scm
491 $ ./palindrome level
492 level is a palindrome
493 $ ./palindrome liver
494 liver isn't a palindrome
496Chicken supports separate compilation, using some extensions to
497Scheme. Let's divide our palindrome program into a library module
498({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
500Here's the external library. We {{declare}} that {{pal-proc}} is a
501`unit', which is the basis of separately-compiled modules in
502Chicken. (Units deal with separate compilation, but don't involve
503separated namespaces; namespaced module systems are available as
506 ;;; Library pal-proc.scm
507 (declare (unit pal-proc))
508 (define (palindrome? x)
509   (define (check left right)
510     (if (>= left right)
511         #t
512         (and (char=? (string-ref x left) (string-ref x right))
513              (check (add1 left) (sub1 right)))))
514   (check 0 (sub1 (string-length x))))
516Next we have some  client code that `uses' this separately-compiled
519 ;;; Client pal-user.scm
520 (declare (uses pal-proc))
521 (let ((arg (car (command-line-arguments))))
522   (display
523    (string-append arg
524                   (if (palindrome? arg)
525                       " is a palindrome\n"
526                       " isn't a palindrome\n"))))
528Now we can compile and link everything together. (We show the compile
529and link operations separately, but they can of course be combined
530into one command.)
532 $ csc -c pal-proc.scm
533 $ csc -c pal-user.scm
534 $ csc -o pal-separate pal-proc.o pal-user.o
535 $ ./pal-separate level
536 level is a palindrome
538=== Installing an egg
540Installing eggs is quite straightforward on systems that support
541dynamic loading (again, that would include *BSD, Linux, Mac OS X,
542Solaris, and Windows).  The command {{chicken-install}} will fetch an
543egg from the master Chicken repository, and install it on your local
546In this example, we install the {{uri}} egg, for parsing Uniform
547Resource Identifiers. The installation produces a lot of output, which
548we have edited for space reasons.
550 $ chicken-install uri
552 The extension uri does not exist.
553 Do you want to download it ? (yes/no/abort) [yes] yes
554 downloading uri.egg from ( eggs/3 80)
555   gzip -d -c ../uri.egg | tar xf -
556 .  /Users/vmanis/local/bin/csc -feature compiling-extension
557      -s -O2 -d1 uri.scm -o -check-imports -emit-exports uri.exports
558 ... (lots of stuff elided)
559 .  rm -fr /Users/vmanis/project/chicken/uri.egg
561First, {{chicken-install}} asks us if we want to download the egg. It
562then uncompresses the egg, compiles the code, and installs the egg in
563the local Chicken repository.
565Now we can use our new egg.
567 #;1> (use uri)
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 ; loading /Users/vmanis/local/lib/chicken/3/ ...
574 #;2> (uri-host (uri ""))
575 ""
577=== Accessing C libraries
579Because Chicken compiles to C, and because a foreign function
580interface is built into the compiler, interfacing to a C library is
581quite straightforward. This means that nearly any facility available
582on the host system is accessible from Chicken, with more or less
585Let's create a simple C library, to demonstrate how this
586works. Here we have a function that will compute and return the '''n'''th
587Fibonacci number. (This isn't a particularly good use of C here,
588because we could write this function just as easily in Scheme, but a
589real example would take far too much space here.)
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 #>
606   extern int fib(int n);
607 <#
608 (define xfib (foreign-lambda int "fib" int))
609 (do ((i 0 (+ i 1))) ((> i 10))
610   (printf "~A " (xfib i)))
611 (newline)
613The syntax {{#>...<#}} allows you to include literal C (typically
614external declarations) in your Chicken code. We access {{fib}} by
615defining a {{foreign-lambda}} for it, in this case saying that the
616function takes one integer argument (the {{int}} after the function
617name), and that it returns an integer result (the {{int}} before.) Now we can invoke
618{{xfib}} as though it were an ordinary Scheme function.
620 $ gcc -c fib.c
621 $ csc -o fib-user fib.o fib-user.scm
622 $ ./fib-user
623 0 1 1 2 3 5 8 13 21 34 55
625Those who are interfacing to substantial C libraries should consider
626using the [[easyffi]] egg.
630Back to [[The User's Manual]]
632Next: [[Basic mode of operation]]
Note: See TracBrowser for help on using the repository browser.