25.07.2014 Views

VDM-10 Language Manual

VDM-10 Language Manual

VDM-10 Language Manual

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Chapter 5. Function Definitions<br />

This proof obligation will ensure that the recursive function will terminate and thus sooner or later<br />

reach the base case.<br />

5.1 Polymorphic Functions<br />

Functions can also be polymorphic. This means that we can create generic functions that can<br />

be used on values of several different types. For this purpose type parameters (or type variables<br />

which are written like normal identifiers prefixed with a @ sign) are used. Consider the polymorphic<br />

function to create an empty bag: 1<br />

✞<br />

empty_bag[@elem] : () +> (map @elem to nat1)<br />

empty_bag() ==<br />

{ |-> }<br />

✡✝<br />

Before we can use the above function, we have to instantiate the function empty bag with a type,<br />

for example integers (see also section 6.12):<br />

✞<br />

emptyInt = empty_bag[int]<br />

✡✝<br />

Now we can use the function emptyInt to create a new bag to store integers. More examples of<br />

polymorphic functions are:<br />

✞<br />

num_bag[@elem] : @elem * (map @elem to nat1) +> nat<br />

num_bag(e, m) ==<br />

if e in set dom m<br />

then m(e)<br />

else 0;<br />

✆<br />

✆<br />

plus_bag[@elem] : @elem * (map @elem to nat1) +><br />

(map @elem to nat1)<br />

plus_bag(e, m) ==<br />

m ++ { e |-> num_bag[@elem](e, m) + 1 }<br />

✡✝<br />

✆<br />

If pre- and or post-conditions are defined for polymorphic functions, the corresponding predicate<br />

functions are also polymorphic. For instance if num bag was defined as<br />

✞<br />

num_bag[@elem] : @elem * (map @elem to nat1) +> nat<br />

1 The examples for polymorphic functions are taken from [Dawes91]. Bags are modelled as maps from the elements to<br />

their multiplicity in the bag. The multiplicity is at least 1, i.e. a non-element is not part of the map, rather than being<br />

mapped to 0.<br />

39

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

Saved successfully!

Ooh no, something went wrong!