You are looking at historical revision 12930 of this page. It may differ significantly from its current revision.
Input & output
Chicken | C | Python | |
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 |
|
|
... |
Write a file with some numbers In practice you'd probably collapse the calls to format and equivalent functions in a single call. |
|
|
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
Perl
for my $key ( keys %my_hash ) { print "$key\n"; }
Getting the number of items in a hash
Chicken
(hash-table-size my-hash)