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.

IntInf (infinite precision integers) from the SML standard library (a library of modules that<br />

comes with the SML distributions). The IntInf module provides a type IntINF.int and a set of<br />

infinite precision integer functions.<br />

A better, larger Fibonacci Function<br />

Idea: Use a type with more Integers (Fortunately, there is IntInf)<br />

use "/usr/share/smlnj/src/smlnj-lib/Util/int-inf.sml";<br />

val zero = IntInf.fromInt 0;<br />

val one = IntInf.fromInt 1;<br />

fun bigfob (0) = (zero,one)<br />

| bigfob (1) = (one,one)<br />

| bigfob (n:int) = let val (a, b) = bigfob(n-1) in (b,IntInf.+(a,b)) end;<br />

fun bigfib (n) = let val (a, _) = bigfob(n) in IntInf.toString(a) end;<br />

c○: Michael Kohlhase 108<br />

We have seen that functions are just objects as any others in SML, only that they have functional<br />

type. If we add the ability to have more than one declaration at at time, we can combine function<br />

declarations for mutually recursive function definitions. In a mutually recursive definition we<br />

define n functions at the same time; as an effect we can use all of these functions in recursive calls.<br />

In our example below, we will define the predicates even and odd in a mutual recursion.<br />

Mutual Recursion<br />

generally, we can make more than one declaration at one time, e.g.<br />

- val pi = 3.14 and e = 2.71;<br />

val pi = 3.14<br />

val e = 2.71<br />

this is useful mainly for function declarations, consider for instance:<br />

fun even (zero) = true<br />

| even (suc(n)) = odd (n)<br />

and odd (zero) = false<br />

| odd(suc(n)) = even (n)<br />

trace: even(4), odd(3), even(2), odd(1), even(0), true.<br />

c○: Michael Kohlhase 109<br />

This mutually recursive definition is somewhat like the children’s riddle, where we define the “left<br />

hand” as that hand where the thumb is on the right side and the “right hand” as that where the<br />

thumb is on the right hand. This is also a perfectly good mutual recursion, only — in contrast to<br />

the even/odd example above — the base cases are missing.<br />

2.3.6 Even more SML: Exceptions and State in SML<br />

Programming with Effects<br />

Until now, our procedures have been characterized entirely by their values on their arguments<br />

(as a mathematical function behaves)<br />

This is not enough, therefore SML also considers effects, e.g. for<br />

59

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

Saved successfully!

Ooh no, something went wrong!