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

Last change on this file since 32618 was 32618, checked in by arthurmaciel, 5 years ago

Added IRC channel to 'CHICKEN repositories, websites, and community'

File size: 23.1 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
173There is also an IRC channel ({{#chicken}}) on [[|Freenode]].
175=== Installing CHICKEN
177CHICKEN is [[/platforms|available]] in binary form for Windows and Linux/x86
178systems, and in source form for all other platforms. Refer to the
179{{README}} file in the distribution for instructions on installing it
180on your system.
182Because it compiles to C, CHICKEN requires that a C compiler be
183installed on your system. (If you're not writing embedded C code, you
184can pretty much ignore the C compiler once you have installed it.)
186* On a Linux system, the GNU Compiler Collection ({{gcc}}) should be
187  installed as part of the basic operating system, or should be
188  available through the package management system (e.g., APT,
189  Synaptic, RPM, or Yum, depending upon your Linux distribution).
190* On Macintosh OS X, you will need the XCode tools, which were shipped
191  on the OS X DVD with older versions of the operating system, and are
192  installable from the App Store with recent versions of the operating
193  system.
194* On Windows, you have three choices.
195** Cygwin ([[]]) provides a relatively
196  full-featured Unix environment for Windows.  CHICKEN works
197  substantially the same in Cygwin and Unix.
198** The GNU Compiler Collection has been ported to Windows, in the
199  MinGW system ([[]]). Unlike Cygwin,
200  executables produced with MinGW do not need the Cygwin DLLs in order
201  to run.   MSys is a companion package to MinGW; it provides a minimum
202  Unix-style development/build environment, again ported from free
203  software.
204*** You can build CHICKEN either with MinGW alone or with MinGW plus
205  MSYS. Both approaches produce a CHICKEN built against the mingw headers
206  and import libraries.
207  The only difference is the environment where you actually run make.
208  {{Makefile.mingw}} is can be used in {{cmd.exe}} with the version of make
209  that comes with mingw.  {{Makefile.mingw-msys}}
210  uses unix commands such as {{cp}} and {{rm}}.  The end product is the
211  same.
213Refer to the {{README}} file for the version you're installing for
214more information on the installation process.
216Alternatively, third party packages in binary format are available.
217See [[/platforms]] for information about how to
218obtain them.
220=== Development environments
222The simplest development environment is a text editor and terminal
223window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for
224using the interpreter and/or calling the compiler. If you
225[[/egg/readline|install the {{readline}} egg]], you
226have all the benefits of command history in the interpreter, Emacs or
227vi-compatible line editing, and customization.
229You will need a text editor that knows Scheme; it's just too painful
230with editors that don't do parenthesis matching and proper
231indentation. Some editors allow you to execute Scheme code directly in
232the editor. This makes programming very interactive: you can type in a
233function and then try it right away. This feature is very highly
236As programmers have very specific tastes about editors, the editors
237listed here are shown in alphabetic order. We aren't about to tell you
238which editor to use, and there may be editors not shown here that
239might satisfy your needs. We would be very interested in reports of
240other editors that have been used with CHICKEN, especially those that
241support interactive evaluation of forms during editing. Pointers to
242these (and to any editor customization files appropriate) should be
243put on the CHICKEN wiki, and will likely be added to future editions
244of this manual. (We have had a request for editors that support
245proportional fonts, in particular.)
247* Emacs ([[]]) is an
248extensible, customizable, self-documenting editor available for
249Linux/Unix, Macintosh, and Windows systems; See
250[[/emacs]] for more information about the available options.
252* Epsilon ([[]]) is a commercial (proprietary) text
253editor whose design was inspired by Emacs. Although Scheme support
254isn't provided, a Lisp mode is available on Lugaru's FTP site, and
255could with some work be made to duplicate the Emacs support. 
257* SciTE ([[]]),
258unlike Emacs or Vim, follows typical graphical UI design conventions
259and control-key mappings, and for simple tasks is as familiar and
260easy to use as Notepad, KEdit, TeachText etc.  However it has many
261programming features such as multiple open files, syntax
262highlighting for a large number of languages (including Lisps),
263matching of brackets, ability to fold sections of code based on the
264matched brackets, column selections, comment/uncomment, and the
265ability to run commands in the same directory as the current file
266(such as make, grep, etc.)  SciTE is written with the GTK toolkit
267and is portable to any GTK platform, including Windows, Linux and
268MacOS.  It uses the Scintilla text-editing component, which lends
269itself well to embedding within other IDEs and graphical toolkits.
270It does not have any other Scheme-specific features, but being
271open-source and modular, features like auto-formatting of
272S-expressions could be added.  The syntax highlighting can be
273configured to use different fonts for different types of syntax,
274including proportional fonts.
276* Vim ([[]]) is a highly configurable text
277editor built to enable efficient and fast text editing. It is an
278improved version of the vi editor distributed with most UNIX
279systems. Vim comes with generic Lisp (and therefore Scheme) editing
280capabilities out of the box. See [[/Vim]]
281for a few tips on using Vim with CHICKEN.
283In the rest of this chapter, we'll assume that you are using an editor
284of your choice and a regular terminal window for executing your
285CHICKEN code.
287=== The Read-Eval-Print loop
289To invoke the CHICKEN interpreter, you use the {{csi}} command.
292 $ csi
295 (c)2008-2010 The Chicken Team
296 (c)2000-2007 Felix L. Winkelmann
297 Version 4.6.0
298 macosx-unix-gnu-x86 [ manyargs dload ptables ]
300 #;1>
302This brings up a brief banner, and then the prompt. You can use this
303pretty much like any other Scheme system, e.g.,
305 #;1> (define (twice f) (lambda (x) (f (f x))))
306 #;2> ((twice (lambda (n) (* n 10))) 3)
307 300
309Suppose  we have already created a file {{fact.scm}} containing a
310function definition.
312 (define (fact n)
313   (if (= n 0)
314       1
315       (* n (fact (- n 1)))))
317We can now load this file and try out the function.
319 #;3> (load "fact.scm")
320 ; loading fact.scm ...
321 #;4> (fact 3)
322 6
324The '''read-eval-print loop''' ('''REPL''') is the component of the
325Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
326and ''prints'' out the result. The REPL's prompt can be customized
327(see the [[Using the interpreter]])
328but the default prompt, showing the number of the form, is quite
331The REPL also supports debugging commands:
332input lines beginning with a {{,}} (comma) are treated as special
333commands. (See the [[Using the interpreter#Toplevel commands|full list]].)
336==== Scripts
338You can use the interpreter to run a Scheme program from the command
339line. For the following example we create a program that does a quick
340search-and-replace on an input file; the arguments are a regular
341expression and a replacement string. First create a file to hold the "data" called ''quickrep.dat'' with your favorite editor holding these lines:
343 xyzabcghi
344 abxawxcgh
345 foonly
347Next create the scheme code in a file called ''quickrep.scm'' with the
348following little program:
350<enscript highlight=scheme>
352(use irregex) ; irregex, the regular expression library, is one of the
353              ; libraries included with CHICKEN.
355(define (process-line line re rplc)
356  (irregex-replace/all re line rplc))
358(define (quickrep re rplc)
359  (let ((line (read-line)))
360    (if (not (eof-object? line))
361        (begin
362          (display (process-line line re rplc))
363          (newline)
364          (quickrep re rplc)))))
366;;; Does a lousy job of error checking!
367(define (main args)
368  (quickrep (irregex (car args)) (cadr args)))
372To run it enter this in your shell:
374 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
375 xyzAghi
376 Agh
377 foonly
379The {{-ss}} option sets several options that work smoothly together to
380execute a script. You can make the command directly executable from
381the shell by inserting a `[[Using the interpreter#Writing Scheme scripts|shebang line]]' at the beginning of the
384The {{-ss}} option arranges to call a procedure named {{main}}, with
385the command line arguments, packed in a list, as its arguments. (There
386are a number of ways this program could be made more idiomatic CHICKEN
387Scheme, see the rest of the manual for details.)
389=== The compiler
391There are several reasons you might want to compile your code.
393* Compiled code executes substantially faster than interpreted
394  code.
395* You might want to deploy an application onto machines where the
396  users aren't expected to have CHICKEN installed: compiled
397  applications can be self-contained.
399The CHICKEN compiler is provided as the command {{chicken}}, but in
400almost all cases, you will want to use the {{csc}} command
401instead. {{csc}} is a convenient driver that automates compiling
402Scheme programs into C, compiling C code into object code, and linking
403the results into an executable file. (Note: in a Windows environment
404with Visual Studio, you may find that {{csc}} refers to Microsoft's
405C# compiler. There are a number of ways of sorting this out, of which
406the simplest is to rename one of the two tools, and/or to
407organize your {{PATH}} according to the task at hand.)
409Compiled code can be intermixed with interpreted code on systems that
410support dynamic loading, which includes modern versions of *BSD,
411Linux, Mac OS X, Solaris, and Windows.
413We can compile our factorial function, producing a file named
414{{}} (`shared object' in Linux-ese, the same file type is used
415in OS X and Windows, rather than {{dylib}} or {{dll}}, respectively).
417 chicken$ csc -dynamic fact.scm
418 chicken$ csi -quiet
419 #;1> (load "")
420 ; loading ...
421 #;2> (fact 6)
422 720
424On any system, we can just compile a program directly into an
425executable. Here's a program that tells you whether its argument is a
428<enscript highlight=scheme>
429(define (palindrome? x)
430  (define (check left right)
431    (if (>= left right)
432        #t
433        (and (char=? (string-ref x left) (string-ref x right))
434             (check (add1 left) (sub1 right)))))
435  (check 0 (sub1 (string-length x))))
436(let ((arg (car (command-line-arguments))))
437  (display
438   (string-append arg
439                  (if (palindrome? arg)
440                      " is a palindrome\n"
441                      " isn't a palindrome\n"))))
444We can compile this program using {{csc}}, creating an executable
445named {{palindrome}}.
447 $ csc -o palindrome palindrome.scm
448 $ ./palindrome level
449 level is a palindrome
450 $ ./palindrome liver
451 liver isn't a palindrome
453CHICKEN supports separate compilation, using some extensions to
454Scheme. Let's divide our palindrome program into a library module
455({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
457Here's the external library. We {{declare}} that {{pal-proc}} is a
458`unit', which is the basis of separately-compiled modules in
459CHICKEN. (Units deal with separate compilation, but don't involve
460separated namespaces; namespaced module systems are available as
463<enscript highlight=scheme>
464;;; Library pal-proc.scm
465(declare (unit pal-proc))
466(define (palindrome? x)
467  (define (check left right)
468    (if (>= left right)
469        #t
470        (and (char=? (string-ref x left) (string-ref x right))
471             (check (add1 left) (sub1 right)))))
472  (check 0 (sub1 (string-length x))))
475Next we have some  client code that `uses' this separately-compiled
478<enscript highlight=scheme>
479;;; Client pal-user.scm
480(declare (uses pal-proc))
481(let ((arg (car (command-line-arguments))))
482  (display
483   (string-append arg
484                  (if (palindrome? arg)
485                      " is a palindrome\n"
486                      " isn't a palindrome\n"))))
489Now we can compile and link everything together. (We show the compile
490and link operations separately, but they can of course be combined
491into one command.)
493 $ csc -c pal-proc.scm
494 $ csc -c pal-user.scm
495 $ csc -o pal-separate pal-proc.o pal-user.o
496 $ ./pal-separate level
497 level is a palindrome
499=== Installing an egg
501Installing eggs is quite straightforward on systems that support
502dynamic loading (again, that would include *BSD, Linux, Mac OS X,
503Solaris, and Windows).  The command {{chicken-install}} will fetch an
504egg from the master CHICKEN repository, and install it on your local
507In this example, we install the {{uri-common}} egg, for parsing
508Uniform Resource Identifiers. The installation produces a lot of
509output, which we have edited for space.
511 $ chicken-install uri-common
513 retrieving ...
514 resolving alias `kitten-technologies' to:
515 connecting to host "", port 80 ...
516 requesting "/henrietta.cgi?name=uri-common&mode=default" ...
517 reading response ...
518 [...]
519 /usr/bin/csc -feature compiling-extension -setup-mode    -s -O2 uri-common.scm -j uri-common
520 /usr/bin/csc -feature compiling-extension -setup-mode    -s -O2 uri-common.import.scm
521 cp -r /usr/lib/chicken/5/
522 chmod a+r /usr/lib/chicken/5/
523 cp -r /usr/lib/chicken/5/
524 chmod a+r /usr/lib/chicken/5/
525 chmod a+r /usr/lib/chicken/5/uri-common.setup-info
527{{chicken-install}} connects to a mirror of the egg repository and
528retrieves the egg contents.  If the egg has any uninstalled
529dependencies, it recursively installs them.  Then it builds the egg
530code and installs the resulting extension into the
531local CHICKEN repository.
533Now we can use our new egg.
535 #;1> (use uri-common)
536 ; loading /usr/lib/chicken/5/ ...
537 ; [... other loaded files omitted for clarity ...]
539 #;2> (uri-host (uri-reference ""))
540 ""
542=== Accessing C libraries
544Because CHICKEN compiles to C, and because a foreign function
545interface is built into the compiler, interfacing to a C library is
546quite straightforward. This means that nearly any facility available
547on the host system is accessible from CHICKEN, with more or less
550Let's create a simple C library, to demonstrate how this
551works. Here we have a function that will compute and return the '''n'''th
552Fibonacci number. (This isn't a particularly good use of C here,
553because we could write this function just as easily in Scheme, but a
554real example would take far too much space here.)
556 /* fib.c */
557 int fib(int n) {
558   int prev = 0, curr = 1;
559   int next;
560   int i;
561   for (i = 0; i < n; i++) {
562     next = prev + curr;
563     prev = curr;
564     curr = next;
565   }
566   return curr;
567 }
569Now we can call this function from CHICKEN.
571 ;;; fib-user.scm
572 #>
573   extern int fib(int n);
574 <#
575 (define xfib (foreign-lambda int "fib" int))
576 (do ((i 0 (+ i 1))) ((> i 10))
577   (printf "~A " (xfib i)))
578 (newline)
580The syntax {{#>...<#}} allows you to include literal C (typically
581external declarations) in your CHICKEN code. We access {{fib}} by
582defining a {{foreign-lambda}} for it, in this case saying that the
583function takes one integer argument (the {{int}} after the function
584name), and that it returns an integer result (the {{int}} before.) Now we can invoke
585{{xfib}} as though it were an ordinary Scheme function.
587 $ gcc -c fib.c
588 $ csc -o fib-user fib.o fib-user.scm
589 $ ./fib-user
590 0 1 1 2 3 5 8 13 21 34 55
592Those who are interfacing to substantial C libraries should consider
593using the [[/egg/bind|bind egg]].
597Back to [[The User's Manual]]
599Next: [[Basic mode of operation]]
Note: See TracBrowser for help on using the repository browser.