PPP Exercises 2: Using Modules
In TL you can use functions defined in modules by using the dot-notation. From a naive point of view, you could see modules as tuples with type and value (mostly function) components. The modules are bundled in different libraries. The following demo will show you how to use functions that belong to modules.
Demo: Interfaces & modules
(* -- define a library 'Root' as module environment: *)
do makeLibraries Root;
(* -- define the module 'print' (with interface 'Print'); *)
(* -- see files 'stdenv/Print.ti' and 'stdenv/print.tm' *)
(* -- for included functions *)
import print;
(* -- use the module 'print' like a tuple with function components: *)
print.string("Hello world.");
print.int(1);
begin print.int(1) print.ln() print.string("Hello") end;
(* -- show the components of module 'print' (see also 'stdenv/Print.ti'): *)
print;
(* -- define the module 'list' (with interface 'List'); *)
(* -- see files 'bulkenv/List.ti' and 'bulkenv/list.tm' *)
(* -- for included functions *)
import list;
(* -- use the module 'list': *)
Let StringList = list.T(String);
let nilList :StringList = list.new(:String);
list.empty(nilList);
list.head(nilList);
let stringList :StringList = list.cons(:String "Hello" nilList);
list.size(stringList);
print.string(list.head(stringList));
let tail = list.tail(stringList);
list.empty(tail);
let stringList1 = list.cons("world" stringList);
print.string(list.head(list.tail(stringList1)));
let infix :: = list.cons;
let nil = list.new;
let iList = 1 :: {2 :: {3 :: nil()}}
Exercise a: Sum of list of integers
Write a function 'addIntList' that adds all integers of a list.
If the list is empty, 0 is returned.
Use the module 'list'.
Test with [9,10,11]
Exercise b: Folding a list of integers
Write a function 'foldIntList' that reduces a list of integers to an integer value, i.e by adding or by multiplying all the integers.
'foldIntList' gets a list of integers, an
initial value of type 'Int' and a function of type 'Fun(:Int :Int)
:Int'. 'foldIntList' applies the function to the initial value and the first
element, then to the result of the first application and the second
element, and so on. It returns the initial value if the list is empty.
Test with (after importing 'int'):
initial = 0, int.add, [1,2,3,4]
initial = 1, int.mul, [1,2,3,4]
Exercise: Convert String to Int
Write a function 'convert' that gets a string of decimal digits and converts this string to an integer. If the string is empty, 0 is returned.
Hint: Use the modules 'string' and 'char'.
Test with "5", "11", "200"
Ulrike Steffens, 1994; Update: Gerald Schröder, 08-may-1995