13.11.2014 Views

Introduction to Computational Linguistics

Introduction to Computational Linguistics

Introduction to Computational Linguistics

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

5. Modules 13<br />

can find out why the program rejects the input. To do this, OCaML lets you define<br />

so–called exceptions. This is done as follows.<br />

(34)<br />

exception Input_is_negative;;<br />

Exceptions always succeed, and they succeed by OCaML typing their name. So,<br />

we improve our definition as follows.<br />

(35)<br />

let rec expt n x<br />

if x < 0 then raise Input_is_negative else<br />

if x = 0 then 1 else<br />

n * (expt n (x-1))<br />

;;<br />

Now look at the following dialog:<br />

(36)<br />

# expt 2 (-3)<br />

Exception:<br />

Input_is_negative<br />

Thus, OCaML quits the computation and raises the exception that you have defined<br />

(there are also inbuilt exceptions). In this way you can make every definition<br />

<strong>to</strong>tal.<br />

Recursive definitions of functions on strings or lists are au<strong>to</strong>matically grounded<br />

if you include a basic clause for the value on the empty string or the empty list,<br />

respectively. It is a common source of error <strong>to</strong> omit such a clause. Beware! However,<br />

recursion can be done in many different ways. For strings, for example, it<br />

does not need <strong>to</strong> be character by character. You can define a function that takes<br />

away two characters at a time, or even more. However, you do need <strong>to</strong> make sure<br />

that the recursion ends somewhere. Otherwise you will not get a reply.<br />

5 Modules<br />

Modules are basically convenient ways <strong>to</strong> package the programs. When the program<br />

gets larger and larger, it is sometimes difficult <strong>to</strong> keep track of all the names<br />

and identifiers. Moreover, one may want <strong>to</strong> identify parts of the programs that

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!