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.

Data Type Declarations<br />

concrete version of abstract data types in SML<br />

- datatype mynat = zero | suc of mynat;<br />

datatype mynat = suc of mynat | zero<br />

this gives us constructor functions zero : mynat and suc : mynat -> mynat.<br />

define functions by (complete) case analysis (abstract procedures)<br />

fun num (zero) = 0 | num (suc(n)) = num(n) + 1;<br />

val num = fn : mynat -> int<br />

fun incomplete (zero) = 0;<br />

stdIn:10.1-10.25 Warning: match nonexhaustive<br />

zero => ...<br />

val incomplete = fn : mynat -> int<br />

fun ic (zero) = 1 | ic(suc(n))=2 | ic(zero)= 3;<br />

stdIn:1.1-2.12 Error: match redundant<br />

zero => ...<br />

suc n => ...<br />

zero => ...<br />

c○: Michael Kohlhase 81<br />

So, we can re-define a type of unary natural numbers in SML, which may seem like a somewhat<br />

pointless exercise, since we have integers already. Let us see what else we can do.<br />

Data Types Example (Enumeration Type)<br />

a type for weekdays (nullary constructors)<br />

datatype day = mon | tue | wed | thu | fri | sat | sun;<br />

use as basis for rule-based procedure (first clause takes precedence)<br />

- fun weekend sat = true<br />

| weekend sun = true<br />

| weekend _ = false<br />

val weekend : day -> bool<br />

this give us<br />

- weekend sun<br />

true : bool<br />

- map weekend [mon, wed, fri, sat, sun]<br />

[false, false, false, true, true] : bool list<br />

nullary constructors describe values, enumeration types finite sets<br />

c○: Michael Kohlhase 82<br />

Somewhat surprisingly, finite enumeration types that are a separate constructs in most programming<br />

languages are a special case of datatype declarations in SML. They are modeled by sets of<br />

base constructors, without any functional ones, so the base cases form the finite possibilities in<br />

this type. Note that if we imagine the Peano Axioms for this set, then they become very simple;<br />

in particular, the induction axiom does not have step cases, and just specifies that the property<br />

P has to hold on all base cases to hold for all members of the type.<br />

Let us now come to a real-world examples for data types in SML. Say we want to supply a library<br />

for talking about mathematical shapes (circles, squares, and triangles for starters), then we can<br />

45

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

Saved successfully!

Ooh no, something went wrong!