15.08.2013 Views

General Computer Science; Problems and Solutions for ... - Kwarc

General Computer Science; Problems and Solutions for ... - Kwarc

General Computer Science; Problems and Solutions for ... - 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.

Problem 1.28 (Unary natural numbers)<br />

Define a datatype nat of unary natural numbers <strong>and</strong> implement the functions<br />

• add = fn : nat * nat -> nat (adds two numbers)<br />

• mul = fn : nat * nat -> nat (multiplies two numbers)<br />

Solution:<br />

datatype nat = zero | s of nat;<br />

fun add(zero:nat,n2:nat) = n2<br />

| add(n1,zero) = n1<br />

| add(s(n1),s(n2)) = s(add(n1,s(n2)));<br />

fun mult(zero:nat,_) = zero<br />

| mult(_,zero) = zero<br />

| mult(n1,s(zero)) = n1<br />

| mult(s(zero),n2) = n2<br />

| mult(n1,s(n2)) = add(n1,mult(n1,n2));<br />

29

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

Saved successfully!

Ooh no, something went wrong!