Previous Contents Next

Exercises

Polymorphic Printing Function

We wish to define a printing function print with type 'a -> unit able to print any Objective CAML value. To this end, we extend and improve the inspect function.

  1. In C, write the function print_ws which prints Objective CAML as follows: The function should handle structured types recursively.

  2. To avoid looping on circular values, and to display sharing properly, modify this function to keep track of the addresses of heap blocks it has already seen. If an address appears several times, name it when it is first printed (v = name), and just print the name when this address is encountered again.
    1. Define a data structure to record the addresses, determine when they occur several times, and associate a name with each address.
    2. Traverse the value once first to determine all the addresses it contains and record them in the data structure.
    3. The second traversal prints the value while naming addresses at their first occurrences.
    4. Define the function print combining both traversals.

Matrix Product

  1. Define an abstract type float_matrix for matrices of floating-point numbers.

  2. Define a C type for these matrices.

  3. Write a C function to convert values of type float array array to values of type float_matrix.

  4. Write a C function performing the reverse conversion.

  5. Add the C functions computing the sum and the product of these matrices.

  6. Interface them with Objective CAML and use them.

Counting Words: Main Program in C

The Unix command wc counts the number of characters, words and lines in a file. The goal of this exercise is to implement this command, while counting repeated words only once.
  1. Write the program wc in C. This program will simply count words, lines and characters in the file whose name is passed on the command line.

  2. Write in Objective CAML a function add_word that uses a hash table to record how many times the function was invoked with the same character string as argument.

  3. Write two functions num_repeated_words and num_unique_words counting respectively the number of word repetitions and the number of unique words, as determined from the hash table built by add_word.

  4. Register the three previous functions so that they can be called from a C program.

  5. Rewrite the main function of the wc program so that it prints the number of unique words instead of the number of words.

  6. Write the main function and the commands required to compile this program as an Objective CAML program.

  7. Write the main function and the commands required to compile this program as a C program.

Previous Contents Next