You are looking at historical revision 8701 of this page. It may differ significantly from its current revision.

Introduction

If you don't know much about chicken yet, please take a moment to read the introductory part of The User's Manual. You're back? Good!

Paradigm independence

The most important design feature of Ruby is that it is purely object-oriented; everything is an object. Scheme is not an object-oriented language. In fact, it does not commit to any particular programming paradigm -- it offers complete and total freedom to the programmer. If you decide (a part of) a program is best implemented in an object-oriented fashion, you can choose to use one of the many object systems. Have a quick glance at Eggs Unlimited 3#object-oriented-programming to get an impression of the diversity of styles of object oriented programming you can use with Chicken. By the way, the list on that page shows all the available eggs for Chicken. We'll explain all about these later.

Besides object-oriented programming, you can also program in a procedural fashion (like you would in Pascal, for example) or in a functional style (a bit like Haskell or ML) and you can even experiment with message-passing like in Erlang or logic programming like you would with Prolog.

Origins

Ruby's origins are firmly rooted in Lisp. It takes many things and ideas from Lisp (symbols, lambdas, eval, metaprogramming, DSLs etc). What it doesn't take from Lisp it takes from Smalltalk, which was itself inspired by Lisp's clean syntax. All this means that once you're over the initial hump of grokking the syntax, you'll find yourself in pretty familiar territory.

Originally, Ruby started out as an implementation-defined language. That is, there was only one implementation (Matz's) and whatever that implementation did was the language spec. Nowadays, new implementations of Ruby are being developed, but as of this writing there is still no official specification on Ruby's syntax and semantics, by my knowledge.

Scheme, on the other hand, is a specification-defined language. There is one official language specification which says what Scheme is and how it works. Chicken is simply an implementation of that specification. There is one thing that is important to know right now: The Scheme specification is extremely minimal in design. It tries to define as few language constructs as possible, but these few should be so powerful that you will not need any more to make programs. This results in an extremely small spec and a very elegant and clean language with very few rules to remember, which makes it easy to learn.

However, in the real world you will need much more than just programming constructs, you need things to interact with the operating system, networking libraries etcetera. That's where the difference between Scheme and other languages comes in: Every implementation of Scheme defines the things it thinks are necessary to build real programs with. Unfortunately, this means most Scheme programs are inherently unportable, but it also means that Scheme implementations are free to experiment how they want and explore new language territory. This gives each Scheme implementation its uniqueness.

Chicken's power is in how it extends the Scheme standard. It has a very comfortable interface to C that does not require you to touch a single line of C code in order to create bindings to existing C libraries, but it also gives you the freedom to embed Chicken in C code or C in Chicken code as you want. It offers a TCP/IP networking layer, it has great POSIX interoperability so you can interact with the OS. And most importantly: It can compile Scheme code to very efficient C code which can itself be compiled to machine code, giving you the best of both worlds: a dynamic language which allows you to program in the flexible way you are used to with Ruby, but this can be compiled for maximum efficiency.

Syntax

The basics

The one thing that is most strikingly different between Ruby and Scheme is of course the syntax. Ruby has an extremely baroque syntax that allows you many freedoms in how you would like to write down things. Scheme, on the other hand, has only one way in which to write a given expression. Let's start by looking at an example. First we start by firing up an irb session and typing a little program:

 irb(main):001:0> # My first program
 irb(main):002:0* [1, 2, 3, 4].map{|x| x + 1}
 => [2, 3, 4, 5]
 irb(main):003:0>

Now, we fire up a csi (chicken scheme interpreter) session:

 #;1> ; My first program
 (map add1 (list 1 2 3 4))
 (2 3 4 5)
 #;2>
 

In Scheme, lists are delimited with parentheses with its elements separated by spaces. As we can see, everything in Scheme is a list, even the expressions that you use to tell it what to do! An expression in Scheme is always a list with the operator on its first position and the operands following it. Procedures that accept no arguments are simply a list with only the procedure in it, for example (newline), which simply displays a newline character.

This simple rule also means that every parenthesis has a meaning. You can't add more parentheses or leave off parentheses like you can in most Ruby expressions. Adding extra parentheses simply applies the resulting expression as if it were a procedure:

 #;2> ((newline))
 Error: call of non-procedure: #<unspecified>
         Call history:
         <syntax>                ((newline))
         <syntax>                (newline)
         <eval>          ((newline))
         <eval>          (newline)       <--

If (newline) returned a procedure, it would be called. But as it happens, newline simply returns an unspecified value which is not a procedure and thus can't be applied. We can also use the result of calling a procedure in the call to another procedure:

 #;3> (add1 2)
 3
 #;4> (- 10 (add1 2) 1)
 6

We see that arithmetic is a little different from Ruby, as a result of the simple rules Scheme has for its syntax. This may be a little awkward, especially with complex calculations:

 #;5> (* (+ 1 (- 6 2) 2) (- 10 5))
 35

In Ruby (and other languages with algebraic syntax) this would have been

 irb(main):002:0> (1 + (6 - 2) + 2) * (10 - 5)
 => 35
 irb(main):003:0> # Alternatively:
 irb(main):004:0* (1 + 6 - 2 + 2) * (10 - 5)
 irb(main):005:0> # or even:
 irb(main):006:0* (((1) + ((((6 - 2)))) + 2) * (((10) - ((5)))))
 => 35

Both types of syntax have their advantages and disadvantages: The Ruby-like syntax is more natural, but you have to think about operator precedence rules. Chicken does not need operator precedence rules because the precedence can be determined from the way it's nested, but it's less natural for most people (though you get used to it very quickly).

Actually, right now you know almost all there is to know about Scheme's syntax! Chicken has a couple of extensions to the basic Scheme syntax, but we won't go into detail here. Later you'll see a couple of handy shorcuts, but this is basically it.

Variables

Variables are names for things. Chicken has vary lax rules for naming variables. Actually, any string is a valid identifier as long as you quote it correctly.

Ruby:

 #;1> x = 10
 => 10
 #;2> x
 => 10
 #;3> x-y-z = 10
 NameError: undefined local variable or method `x' for main:Object
       from (irb):2
 

Scheme:

 #;1> (define x 10)
 #;2> x
 10
 #;3> (define x-y-z 10)
 #;4> x-y-z
 10
 #;5> (define %x% 1)
 #;6> %x%
 1
 #;7> (define |a b c| 5)
 #;8> |a b c|
 5

As you can see, because of Scheme's operator rules, symbols that would normally be separate tokens designating operators have no special meaning so we can use it in the middle of a name. The convention in Scheme is to use the minus sign as word separator (in Ruby, you would use an underscore for separating words). The final example shows how any string is allowed as a variable name: if the string contains syntax that would mean something else to Scheme you can enclose the variable name in pipe symbols. The pipe symbol itself can be escaped with a backslash, if you need it to be part of a variable.

Procedures

Of course using simple expressions like this is not enough. You'll need procedures too. In Ruby, named procedures are actually methods on objects, but we can forget about that little detail for now:

Ruby:

  def pythagoras(a, b)
    Math.sqrt(a**2 + b**2)
  end

Chicken:

  (define pythagoras
    (lambda (a b)
      (sqrt (* a a) (* b b))))

Now that's interesting! Procedures are just regular variables in Scheme (a bit like functions in Javascript). We assign a lambda to it. We can do that in Ruby too, but it's not pretty:

Ruby:

 some_class.send(:define_method, :pythagoras) {|a, b| Math.sqrt(a**2 + b**2) }

Just like in Ruby the def foo is shorter than the above, in Scheme we have a convenient shorthand for defining procedures too:

  (define (pythagoras a b)
    (sqrt (* a a) (* b b)))

To assign to a pre-existing variable we can also use set!:

 #;1> (define x 10)
 #;2> x
 10
 #;3> (set! x 20)
 #;4> x
 20

Top-level variables can also be overwritten by simply redefining them, but in some cases you need set!. However, set! is a typical artifact of an imperative programming style and in clean code you want to avoid using it.

Data types

Now we have a basic grasp of Scheme's syntax, we can have a look at the different data types Chicken has to offer. We will do this from a Ruby perspective.

Strings

Strings are simple. Just like in Ruby, we have strings enclosed by double quotes: "foo" works the same in Ruby as it does in Chicken. Chicken's double quoted strings work more like Ruby's single-quoted strings, though. There is no string interpolation and other things; a string is just a string.

Ruby:

 x = 10
 y = "x contains #{x}"
 z = "x contains " + x.to_s

Scheme:

 (define x 10)
 (define y (sprintf "x contains ~A" x))
 (define z (conc "x contains " x))
 ; Or:
 (define z (string-append "x contains " (->string x)))

Note that ->string is simply the name of a procedure, including the arrow.

Arrays

In Ruby we use arrays for storing lists of things. The obvious Scheme equivalent type is the list, you'd think. This is sort of true:

Ruby:

 x = [1, 2, 3, 4]
 x.map{|y| x + 10 }
 x.each{|y| puts y }

Scheme:

 (define x '(1 2 3))
 (map x (lambda (x) (+ x 10)))
 (for-each (lambda (x) (display x) (newline)) x)

Note that Scheme does not have the block scoping bug. Another thing that we should note is the first line. We create a list by quoting it. This allows us to enter the list in such a way that Chicken knows the list is just that; a list, and not a procedure application of the procedure called 1 on the arguments 2 and 3. The apostrophe takes care of that.

However, we must always remember that the Scheme list is more like a linked list. This means that it is very flexible in how we can add things to it and alter it, but it also means that traversing it takes more time as more items are added to it. Accessing an element is an O(n) operation, where n is the position of the element.

If we want O(1) operations on our lists, we can use a vector:

 #;1> (define x (vector 1 2 3 4))
 #;2> (vector-ref x 2)
 3
 #;3> (define y (list 1 2 3 4))
 #;4> (list-ref y 2)
 3

Adding new elements to a vector requires resizing or even copying the vector, just like it would in Ruby. So whenever you're contemplating using a list type, think about the properties you want the list type to have. This may sound odd, but in fact this gives you much more flexibility than Ruby, where you have the choice of using an Array, or... using an Array. However, as Knuth famously said: "Premature optimization is the root of all evil", and you should probably take the list solution until it's proven that you need vectors. Also, because Lisp was built on lists, it is very good at manipulating them, so they're most likely the most convenient datatype.

Chicken also offers you several other types of array-like types, each with their own unique time and space properties. Which you'll use depends on the task at hand and the situations your system will be used under.

Symbols

Luckily, you are a Ruby programmer, so we will not have to go through the whole "explaining what symbols exactly are" again :) Actually, Ruby borrowed symbols from Lisp.

Ruby:

 "foo".to_sym

Scheme:

 (string->symbol "foo")

To enter them literally, we can use this syntax:

Ruby:

 :foo

Scheme:

 'foo

As we can see, a symbol is only a quoted variable name! This is the origin of symbols and also the reason you can send symbols representing method names to objects in Ruby. Symbols have all the same semantics as Ruby's symbols: they can be compared in constant time and they take up very little memory space.

Examples

Let's look at a few larger programs to better appreciate how one would program in Chicken.

 TODO

Chicken and the Real World

Programming is about more than having a pretty language, so let's look at what Chicken has to offer for real construction work.

Eggs

Eggs are to chicken what gems are to Ruby: installable extensions like libraries and programs. The list of eggs is where you should look first when you are going to implement something big. You can install an egg almost like you install a gem, as follows:

 $ chicken-setup runcmd

This downloads and installs the egg with the name "runcmd". This egg has no dependencies, but if it did it would have downloaded and installed them as well.

Meta programming

A hot topic in the Ruby community is meta programming and DSLs (Domain specific languages). These ideas originated from Lisp, which means you can just keep on trucking in Chicken!

Data is code and code is data

The most fundamental concept of Lisp is that code is data. As we've seen, procedure calls look like lists. We've also seen that we can quote lists to "block" Scheme from interpreting a list as a procedure call. We can also turn this around on its head and force a list to be evaluated as code:

 #;1> (define calculate '(+ 1 2 3 4))
 #;2> calculate
 (+ 1 2 3 4)
 #;3> (eval calculate)
 10
 #;4>

"Big deal", you might say, "Ruby also has eval". But the difference is what matters: In Ruby you have to construct strings to be evaluated, which means you need to be able to parse strings if you want to change a Ruby-program-stored-as-string. In Scheme we can simply hack the list. The program is stored in a parsed state, so to speak.

If we would want to change the operator from + to *, we can simply do that:

 #;1> (eval (cons '* (cdr calculate)))
 24

This is much more robust than any regexp hacking or ad-hoc parsing on strings you want to evaluate.

Macros

One of the coolest concepts, but also the one most easily abused is macros. Because Scheme stores code as data, you can change the code on-the-fly as described above. You can do that at run-time on random data through eval, but you can also do it at compile-time on your program, which is usually the best time to do it.

 TODO