You are looking at historical revision 38689 of this page. It may differ significantly from its current revision.
Input & output
CHICKEN | C | Python | Perl | |
Formatting and printing to stdout |
|
printf("I want %d %s\n", count, desc); |
|
|
Printing to stderr |
|
fprintf(stderr, "Ooops\n"); | ... |
|
Reading a line from stdin |
|
|
... |
|
Opening a file for input |
|
|
... |
|
Opening a file for output |
|
|
... |
|
Count lines in a file |
|
|
... |
|
Counting lines in a file if you don't want to keep an entire line in memory at any time: |
|
... |
|
... |
Write a file with some numbers In practice you'd probably collapse the calls to format and equivalent functions in a single call. |
|
|
... |
|
Usage in a compiled program
Some of the procedures listed here, e.g. (read-line) and (format ...), are in the extras namespace, so if you are going to compile your program with csc, you'll need to add the following to your source file:
(use extras)
Lists
Vectors
Declaring a vector of numbers | An anonymous vector is declared as:
|
|
|
Obtaining the size of a vector |
|
If the size of the vector is known at compile time:
|
|
Printing a vector | If you don't care that much about the format used:
|
|
... |
Hash tables
Creating a hash table
CHICKEN
(make-hash-table)
If you need to populate the hash table, you'll probably use alist->hash-table:
(alist->hash-table '((1 . "uno") (2 . "dos")))
Note that the list can be created at runtime.
C++ STL
map<int, string> my_hash; my_hash[1] = "uno"; my_hash[2] = "dos";
Perl
my %hash = ( 1 => 'uno', 2 => 'dos' );
Obtaining an element from a hash
CHICKEN
(hash-table-ref/default my_hash 2 #f)
This will return #f (false) if the element is not defined. If you prefer to have an error thrown, you should use:
(hash-table-ref my_hash 2)
C++ STL
my_hash[2]
Python
my_hash[2]
Perl
$my_hash{2}
Printing the keys in the hash
CHICKEN
If you can afford to have a list with the keys created, you should do this:
(format #t "~{~A~%~}~%" (hash-table-keys my_hash))
Otherwise, do this:
(hash-table-walk
my-hash
(lambda (key value)
(format #f "~A~%" key)))
C++ STL
for(map<int, string>::iterator iter = my_hash.begin(); it != my_hash.end(); ++it ) cout << it->first << endl;
Python
print my_hash.keys()
Perl
say foreach keys %my_hash;
Getting the number of items in a hash
CHICKEN
(hash-table-size my-hash)
Python
len(my-hash)