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

Last change on this file since 25875 was 25875, checked in by felix winkelmann, 9 years ago

merged some manual changes from master into wiki

File size: 23.0 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.
61CHICKEN is an implementation of Scheme that has many advantages.
63CHICKEN Scheme combines an optimising compiler with a reasonably fast
64interpreter.  It supports almost all of R5RS and the important SRFIs.
65The compiler generates portable C code that supports tail recursion,
66first-class continuations, and lightweight threads, and the interface to
67and from C libraries is flexible, efficient, and easy to use.  There are
68hundreds of contributed CHICKEN libraries that make the programmer's
69task easier.  The interpreter allows interactive use, fast prototyping,
70debugging, and scripting.  The active and helpful CHICKEN community
71fixes bugs and provides support.  Extensive documentation is supplied.
73CHICKEN was developed by Felix L. Winkelmann over the period from 2000
74through 2007. In early 2008, Felix
75asked the community to take over the responsibility of developing and
76maintaining the system, though he still takes a strong interest in it,
77and participates actively.
79CHICKEN includes
81* a Scheme interpreter that supports almost all of  R5RS Scheme, with
82  only a few relatively minor omissions, and with many extensions
83* a compatible compiler whose target is C, thus making porting to new
84  machines and architectures relatively straightforward
85** the C support allows Scheme code to include `embedded' C code,
86  thus making it relatively easy to invoke host OS or library
87  functions
88* a framework for language extensions, library modules that broaden
89  the functionality of the system
91This package is distributed under the '''BSD license''' and as such is free
92to use and modify.
94Scheme cognoscenti will appreciate the method of compilation and the
95design of the runtime-system, which follow closely Henry Baker's
96[[|CONS Should Not
97CONS Its Arguments, Part II: Cheney on the M.T.A.]] paper and expose a
98number of interesting properties.
100* Consing (creation of data on the heap) is relatively inexpensive,
101  because a generational garbage collection scheme is used, in which
102  short-lived data structures are reclaimed extremely quickly.
104* Moreover, {{call-with-current-continuation}} is practically for free
105  and CHICKEN does not suffer under any performance penalties if
106  first-class continuations are used in complex ways.
108The generated C code is fully tail-recursive.
110Some of the features supported by CHICKEN:
112* SRFIs 0, 1, 2, 4, 6, 8-18, 23, 26, 28, 30, 31, 39, 46, 55, 61, 62, 69, 85, 88 and 98.
113* Lightweight threads based on first-class continuations
114* Record structures
115* Extended comment- and string-literal syntaxes
116* Libraries for regular expressions, string handling
117* UNIX system calls and extended data structures
118* Create interpreted or compiled shell scripts written in Scheme for
119  UNIX or Windows
120* Compiled C files can be easily distributed
121* Allows the creation of fully self-contained statically linked executables
122* On systems that support it, compiled code can be loaded dynamically
123* Built-in support for cross-compilation and deployment
125CHICKEN has been used in many environments ranging from embedded
126systems through desktop machines to large-scale server deployments. 
127The number of language extensions, or '''eggs''', is constantly growing.
129* extended language features
130* development tools, such as documentation generators, debugging, and
131  automated testing libraries
132* interfaces to other languages such as Java, Python, and Objective-C
133* interfaces to database systems, GUIs, and other large-scale
134  libraries,
135* network applications, such as servers and clients for ftp,
136  smtp/pop3, irc, and http 
137* web servers and related tools, including URL parsing, HTML
138  generation, AJAX, and HTTP session management
139* data formats, including XML, JSON, and Unicode support
141CHICKEN is supported by SWIG (Simplified Wrapper and Interface
142Generator), a tool that produces quick-and-dirty interface modules
143for C libraries ([[]]).
145This chapter provides you with an overview of the entire system, with
146enough information to get started writing and running small Scheme
149=== CHICKEN repositories, websites, and community
151The master CHICKEN website is
152[[]]. Here you can find
153basic information about CHICKEN, downloads, and pointers to other key
156The CHICKEN wiki ([[]]) contains the most
157current version of the User's manual, along with various tutorials and
158other useful documents. The list of eggs is at
161A very useful search facility for questions about CHICKEN is found at
162[[]]. The CHICKEN issue tracker is at
165The CHICKEN community has two major mailing lists. If you are a
166CHICKEN user, {{chicken-users}}
167([[]]) will be
168of interest. The crew working on the CHICKEN system itself uses the
169very low-volume {{chicken-hackers}} list
170([[]]) for
173=== Installing CHICKEN
175CHICKEN is available in binary form for Windows and Linux/x86
176systems, and in source form for all other platforms. Refer to the
177{{README}} file in the distribution for instructions on installing it
178on your system.
180Because it compiles to C, CHICKEN requires that a C compiler be
181installed on your system. (If you're not writing embedded C code, you
182can pretty much ignore the C compiler once you have installed it.)
184* On a Linux system, the GNU Compiler Collection ({{gcc}}) should be
185  installed as part of the basic operating system, or should be
186  available through the package management system (e.g., APT,
187  Synaptic, RPM, or Yum, depending upon your Linux distribution).
188* On Macintosh OS X, you will need the XCode tools, which are shipped
189  on the OS X DVD with recent versions of the operating system.
190* On Windows, you have three choices.
191** Cygwin ([[]]) provides a relatively
192  full-featured Unix environment for Windows.  CHICKEN works
193  substantially the same in Cygwin and Unix.
194** The GNU Compiler Collection has been ported to Windows, in the
195  MinGW system ([[]]). Unlike Cygwin,
196  executables produced with MinGW do not need the Cygwin DLLs in order
197  to run.   MSys is a companion package to MinGW; it provides a minimum
198  Unix-style development/build environment, again ported from free
199  software.
200*** You can build CHICKEN either with MinGW alone or with MinGW plus
201  MSYS. Both approaches produce a CHICKEN built against the mingw headers
202  and import libraries.
203  The only difference is the environment where you actually run make.
204  {{Makefile.mingw}} is can be used in {{cmd.exe}} with the version of make
205  that comes with mingw.  {{Makefile.mingw-msys}}
206  uses unix commands such as {{cp}} and {{rm}}.  The end product is the
207  same.
209Refer to the {{README}} file for the version you're installing for
210more information on the installation process.
212Alternatively, third party packages in binary format are available.
213Se [[]] for information about how to
214obtain them.
216=== Development environments
218The simplest development environment is a text editor and terminal
219window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for
220using the interpreter and/or calling the compiler. If you
221[[/egg/readline|install the {{readline}} egg]], you
222have all the benefits of command history in the interpreter, Emacs or
223vi-compatible line editing, and customization.
225You will need a text editor that knows Scheme; it's just too painful
226with editors that don't do parenthesis matching and proper
227indentation. Some editors allow you to execute Scheme code directly in
228the editor. This makes programming very interactive: you can type in a
229function and then try it right away. This feature is very highly
232As programmers have very specific tastes about editors, the editors
233listed here are shown in alphabetic order. We aren't about to tell you
234which editor to use, and there may be editors not shown here that
235might satisfy your needs. We would be very interested in reports of
236other editors that have been used with CHICKEN, especially those that
237support interactive evaluation of forms during editing. Pointers to
238these (and to any editor customization files appropriate) should be
239put on the CHICKEN wiki, and will likely be added to future editions
240of this manual. (We have had a request for editors that support
241proportional fonts, in particular.)
243* Emacs ([[]]) is an
244extensible, customizable, self-documenting editor available for
245Linux/Unix, Macintosh, and Windows systems; See
246[[/emacs]] for more information about the available options.
248* Epsilon ([[]]) is a commercial (proprietary) text
249editor whose design was inspired by Emacs. Although Scheme support
250isn't provided, a Lisp mode is available on Lugaru's FTP site, and
251could with some work be made to duplicate the Emacs support. 
253* SciTE ([[]]),
254unlike Emacs or Vim, follows typical graphical UI design conventions
255and control-key mappings, and for simple tasks is as familiar and
256easy to use as Notepad, KEdit, TeachText etc.  However it has many
257programming features such as multiple open files, syntax
258highlighting for a large number of languages (including Lisps),
259matching of brackets, ability to fold sections of code based on the
260matched brackets, column selections, comment/uncomment, and the
261ability to run commands in the same directory as the current file
262(such as make, grep, etc.)  SciTE is written with the GTK toolkit
263and is portable to any GTK platform, including Windows, Linux and
264MacOS.  It uses the Scintilla text-editing component, which lends
265itself well to embedding within other IDEs and graphical toolkits.
266It does not have any other Scheme-specific features, but being
267open-source and modular, features like auto-formatting of
268S-expressions could be added.  The syntax highlighting can be
269configured to use different fonts for different types of syntax,
270including proportional fonts.
272* Vim ([[]]) is a highly configurable text
273editor built to enable efficient and fast text editing. It is an
274improved version of the vi editor distributed with most UNIX
275systems. Vim comes with generic Lisp (and therefore Scheme) editing
276capabilities out of the
277box. A few tips on using Vim with CHICKEN can be found at
280In the rest of this chapter, we'll assume that you are using an editor
281of your choice and a regular terminal window for executing your
282CHICKEN code.
284=== The Read-Eval-Print loop
286To invoke the CHICKEN interpreter, you use the {{csi}} command.
289 $ csi
292 (c)2008-2010 The Chicken Team
293 (c)2000-2007 Felix L. Winkelmann
294 Version 4.6.0
295 macosx-unix-gnu-x86 [ manyargs dload ptables ]
297 #;1>
299This brings up a brief banner, and then the prompt. You can use this
300pretty much like any other Scheme system, e.g.,
302 #;1> (define (twice f) (lambda (x) (f (f x))))
303 #;2> ((twice (lambda (n) (* n 10))) 3)
304 300
306Suppose  we have already created a file {{fact.scm}} containing a
307function definition.
309 (define (fact n)
310   (if (= n 0)
311       1
312       (* n (fact (- n 1)))))
314We can now load this file and try out the function.
316 #;3> (load "fact.scm")
317 ; loading fact.scm ...
318 #;4> (fact 3)
319 6
321The '''read-eval-print loop''' ('''REPL''') is the component of the
322Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
323and ''prints'' out the result. The REPL's prompt can be customized
324(see the [[Using the interpreter]])
325but the default prompt, showing the number of the form, is quite
328The REPL also supports debugging commands:
329input lines beginning with a {{,}} (comma) are treated as special
330commands. (See the [[Using the interpreter#Toplevel commands|full list]].)
333==== Scripts
335You can use the interpreter to run a Scheme program from the command
336line. For the following example we create a program that does a quick
337search-and-replace on an input file; the arguments are a regular
338expression and a replacement string. First create a file to hold the "data" called ''quickrep.dat'' with your favorite editor holding these lines:
340 xyzabcghi
341 abxawxcgh
342 foonly
344Next create the scheme code in a file called ''quickrep.scm'' with the
345following little program:
347<enscript highlight=scheme>
349(use irregex) ; irregex, the regular expression library, is one of the
350              ; libraries included with CHICKEN.
352(define (process-line line re rplc)
353  (irregex-replace/all re line rplc))
355(define (quickrep re rplc)
356  (let ((line (read-line)))
357    (if (not (eof-object? line))
358        (begin
359          (display (process-line line re rplc))
360          (newline)
361          (quickrep re rplc)))))
363;;; Does a lousy job of error checking!
364(define (main args)
365  (quickrep (irregex (car args)) (cadr args)))
369To run it enter this in your shell:
371 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
372 xyzAghi
373 Agh
374 foonly
376The {{-ss}} option sets several options that work smoothly together to
377execute a script. You can make the command directly executable from
378the shell by inserting a `[[Using the interpreter#Writing Scheme scripts|shebang line]]' at the beginning of the
381The {{-ss}} option arranges to call a procedure named {{main}}, with
382the command line arguments, packed in a list, as its arguments. (There
383are a number of ways this program could be made more idiomatic CHICKEN
384Scheme, see the rest of the manual for details.)
386=== The compiler
388There are several reasons you might want to compile your code.
390* Compiled code executes substantially faster than interpreted
391  code.
392* You might want to deploy an application onto machines where the
393  users aren't expected to have CHICKEN installed: compiled
394  applications can be self-contained.
396The CHICKEN compiler is provided as the command {{chicken}}, but in
397almost all cases, you will want to use the {{csc}} command
398instead. {{csc}} is a convenient driver that automates compiling
399Scheme programs into C, compiling C code into object code, and linking
400the results into an executable file. (Note: in a Windows environment
401with Visual Studio, you may find that {{csc}} refers to Microsoft's
402C# compiler. There are a number of ways of sorting this out, of which
403the simplest is to rename one of the two tools, and/or to
404organize your {{PATH}} according to the task at hand.)
406Compiled code can be intermixed with interpreted code on systems that
407support dynamic loading, which includes modern versions of *BSD,
408Linux, Mac OS X, Solaris, and Windows.
410We can compile our factorial function, producing a file named
411{{}} (`shared object' in Linux-ese, the same file type is used
412in OS X and Windows, rather than {{dylib}} or {{dll}}, respectively).
414 chicken$ csc -dynamic fact.scm
415 chicken$ csi -quiet
416 #;1> (load "")
417 ; loading ...
418 #;2> (fact 6)
419 720
421On any system, we can just compile a program directly into an
422executable. Here's a program that tells you whether its argument is a
425<enscript highlight=scheme>
426(define (palindrome? x)
427  (define (check left right)
428    (if (>= left right)
429        #t
430        (and (char=? (string-ref x left) (string-ref x right))
431             (check (add1 left) (sub1 right)))))
432  (check 0 (sub1 (string-length x))))
433(let ((arg (car (command-line-arguments))))
434  (display
435   (string-append arg
436                  (if (palindrome? arg)
437                      " is a palindrome\n"
438                      " isn't a palindrome\n"))))
441We can compile this program using {{csc}}, creating an executable
442named {{palindrome}}.
444 $ csc -o palindrome palindrome.scm
445 $ ./palindrome level
446 level is a palindrome
447 $ ./palindrome liver
448 liver isn't a palindrome
450CHICKEN supports separate compilation, using some extensions to
451Scheme. Let's divide our palindrome program into a library module
452({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
454Here's the external library. We {{declare}} that {{pal-proc}} is a
455`unit', which is the basis of separately-compiled modules in
456CHICKEN. (Units deal with separate compilation, but don't involve
457separated namespaces; namespaced module systems are available as
460<enscript highlight=scheme>
461;;; Library pal-proc.scm
462(declare (unit pal-proc))
463(define (palindrome? x)
464  (define (check left right)
465    (if (>= left right)
466        #t
467        (and (char=? (string-ref x left) (string-ref x right))
468             (check (add1 left) (sub1 right)))))
469  (check 0 (sub1 (string-length x))))
472Next we have some  client code that `uses' this separately-compiled
475<enscript highlight=scheme>
476;;; Client pal-user.scm
477(declare (uses pal-proc))
478(let ((arg (car (command-line-arguments))))
479  (display
480   (string-append arg
481                  (if (palindrome? arg)
482                      " is a palindrome\n"
483                      " isn't a palindrome\n"))))
486Now we can compile and link everything together. (We show the compile
487and link operations separately, but they can of course be combined
488into one command.)
490 $ csc -c pal-proc.scm
491 $ csc -c pal-user.scm
492 $ csc -o pal-separate pal-proc.o pal-user.o
493 $ ./pal-separate level
494 level is a palindrome
496=== Installing an egg
498Installing eggs is quite straightforward on systems that support
499dynamic loading (again, that would include *BSD, Linux, Mac OS X,
500Solaris, and Windows).  The command {{chicken-install}} will fetch an
501egg from the master CHICKEN repository, and install it on your local
504In this example, we install the {{uri-common}} egg, for parsing
505Uniform Resource Identifiers. The installation produces a lot of
506output, which we have edited for space.
508 $ chicken-install uri-common
510 retrieving ...
511 resolving alias `kitten-technologies' to:
512 connecting to host "", port 80 ...
513 requesting "/henrietta.cgi?name=uri-common&mode=default" ...
514 reading response ...
515 [...]
516 /usr/bin/csc -feature compiling-extension -setup-mode    -s -O2 uri-common.scm -j uri-common
517 /usr/bin/csc -feature compiling-extension -setup-mode    -s -O2 uri-common.import.scm
518 cp -r /usr/lib/chicken/5/
519 chmod a+r /usr/lib/chicken/5/
520 cp -r /usr/lib/chicken/5/
521 chmod a+r /usr/lib/chicken/5/
522 chmod a+r /usr/lib/chicken/5/uri-common.setup-info
524{{chicken-install}} connects to a mirror of the egg repository and
525retrieves the egg contents.  If the egg has any uninstalled
526dependencies, it recursively installs them.  Then it builds the egg
527code and installs the resulting extension into the
528local CHICKEN repository.
530Now we can use our new egg.
532 #;1> (use uri-common)
533 ; loading /usr/lib/chicken/5/ ...
534 ; [... other loaded files omitted for clarity ...]
536 #;2> (uri-host (uri-reference ""))
537 ""
539=== Accessing C libraries
541Because CHICKEN compiles to C, and because a foreign function
542interface is built into the compiler, interfacing to a C library is
543quite straightforward. This means that nearly any facility available
544on the host system is accessible from CHICKEN, with more or less
547Let's create a simple C library, to demonstrate how this
548works. Here we have a function that will compute and return the '''n'''th
549Fibonacci number. (This isn't a particularly good use of C here,
550because we could write this function just as easily in Scheme, but a
551real example would take far too much space here.)
553 /* fib.c */
554 int fib(int n) {
555   int prev = 0, curr = 1;
556   int next;
557   int i;
558   for (i = 0; i < n; i++) {
559     next = prev + curr;
560     prev = curr;
561     curr = next;
562   }
563   return curr;
564 }
566Now we can call this function from CHICKEN.
568 ;;; fib-user.scm
569 #>
570   extern int fib(int n);
571 <#
572 (define xfib (foreign-lambda int "fib" int))
573 (do ((i 0 (+ i 1))) ((> i 10))
574   (printf "~A " (xfib i)))
575 (newline)
577The syntax {{#>...<#}} allows you to include literal C (typically
578external declarations) in your CHICKEN code. We access {{fib}} by
579defining a {{foreign-lambda}} for it, in this case saying that the
580function takes one integer argument (the {{int}} after the function
581name), and that it returns an integer result (the {{int}} before.) Now we can invoke
582{{xfib}} as though it were an ordinary Scheme function.
584 $ gcc -c fib.c
585 $ csc -o fib-user fib.o fib-user.scm
586 $ ./fib-user
587 0 1 1 2 3 5 8 13 21 34 55
589Those who are interfacing to substantial C libraries should consider
590using the [[/egg/bind|bind egg]].
594Back to [[The User's Manual]]
596Next: [[Basic mode of operation]]
Note: See TracBrowser for help on using the repository browser.