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 6. Expressions<br />

where e1 is a boolean expression, while e2 and e3 are expressions of any type. The if<br />

expression denotes the value of e2 evaluated in the given context if e1 evaluates to true in<br />

the given context. Otherwise the if expression denotes the value of e3 evaluated in the given<br />

context. The use of an elseif expression is simply a shorthand for a nested if then else<br />

expression in the else part of the expression.<br />

The cases expression has the form<br />

✞<br />

✡✝<br />

cases e :<br />

p11, p12, ..., p1n -> e1,<br />

... -> ...,<br />

pm1, pm2, ..., pmk -> em,<br />

others<br />

-> emplus1<br />

end<br />

where e is an expression of any type, all pij’s are patterns which are matched one by one<br />

against the expression e. The ei’s are expressions of any type, and the keyword others<br />

and the corresponding expression emplus1 are optional. The cases expression denotes the<br />

value of the ei expression evaluated in the context in which one of the pij patterns has been<br />

matched against e. The chosen ei is the first entry where it has been possible to match the<br />

expression e against one of the patterns. If none of the patterns match e an others clause<br />

must be present, and then the cases expression denotes the value of emplus1 evaluated in<br />

the given context.<br />

Examples: The if expression in the <strong>VDM</strong> languages corresponds to what is used in most programming<br />

languages, while the cases expression in the <strong>VDM</strong> languages is more general than most<br />

programming languages. This is shown by the fact that real pattern matching is taking place,<br />

but also because the patterns do not have to be constants as in most programming languages.<br />

An example of the use of conditional expressions is provided by the specification of the<br />

mergesort algorithm:<br />

✞<br />

lmerge : seq of nat * seq of nat -> seq of nat<br />

lmerge (s1,s2) ==<br />

if s1 = []<br />

then s2<br />

elseif s2 = []<br />

then s1<br />

elseif (hd s1) < (hd s2)<br />

then [hd s1] ˆ (lmerge (tl s1, s2))<br />

else [hd s2] ˆ (lmerge (s1, tl s2));<br />

mergesort : seq of nat -> seq of nat<br />

47<br />

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

Saved successfully!

Ooh no, something went wrong!