15.08.2013 Views

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

epresent them as a data type, where the constructors conform to the three basic shapes they are<br />

in. So a circle of radius r would be represented as the constructor term Circle $r$ (what else).<br />

Data Types Example (Geometric Shapes)<br />

describe three kinds of geometrical forms as mathematical objects<br />

r<br />

Circle (r)<br />

a<br />

Square (a)<br />

Mathematically: R + ⊎ R + ⊎ ((R + × R + × R + ))<br />

In SML: approximate R + by the built-in type real.<br />

datatype shape =<br />

Circle of real<br />

| Square of real<br />

| Triangle of real * real * real<br />

This gives us the constructor functions<br />

Circle : real -> shape<br />

Square : real -> shape<br />

Triangle : real * real * real -> shape<br />

Some experiments:<br />

- Circle 4.0<br />

Circle 4.0 : shape<br />

- Square 3.0<br />

Square 3.0 : shape<br />

- Triangle(4.0, 3.0, 5.0)<br />

Triangle(4.0, 3.0, 5.0) : shape<br />

c○: Michael Kohlhase 83<br />

Data Types Example (Areas of Shapes)<br />

a procedure that computes the area of a shape:<br />

a<br />

c<br />

b<br />

Triangle (a, b, c)<br />

- fun area (Circle r) = Math.pi*r*r<br />

| area (Square a) = a*a<br />

| area (Triangle(a,b,c)) = let val s = (a+b+c)/2.0<br />

in Math.sqrt(s*(s-a)*(s-b)*(s-c))<br />

end<br />

val area : shape -> real<br />

New Construct: Standard structure Math (see [SML10])<br />

some experiments<br />

- area (Square 3.0)<br />

9.0 : real<br />

- area (Triangle(6.0, 6.0, Math.sqrt 72.0))<br />

18.0 : real<br />

c○: Michael Kohlhase 84<br />

46

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

Saved successfully!

Ooh no, something went wrong!