fun t(0)= 0 | t(n)= 2+t(n-1);This definition should be read as two equations. The first equations states that t is defined to be 0 if the input is 0 the second equation states that where n is not 0 the value of t(n) is "2 more than t(n-1)". This defines t for all non-negative values, moreover it gives us a means of calculating t for any non-negative value.
We have an equation which gives the value of t(0) | ||
t(0) | = 0 | From the first equation: fun t(0)= 0 |
We can deduce that t(1)=2 using the defining equations and the above result. | ||
t(1) | = 2 + t(1-1) | Using the second equation: | t(n)= 2 + t(n-1) with 1 for n |
= 2 + t(0) | ||
= 2 + 0 | We know that t(0) = 0 from the above calculation | |
= 2 | ||
Similarly we can calculate t(2) | ||
t(2) | = 2 + t(2-1) | From the 2nd equation with 2 for n |
= 2 + t(1) | ||
= 2 + 2 | ||
= 4 | ||
and we can calculate t(3) | ||
t(3) | = 2 + t(2) | |
= 2 + 4 | ||
= 6 |
Paste each of the following function definitions into ML and evaluate each a a few values. Be sure that you can see
fun d(0)= "de" | d(n)= "do"^d(n-1)^"da"; fun h(0)= 1 | h(n)= h(n-1)+h(n-1); fun m(a,0) = 0 | m(a,b) = a+m(a,b-1); fun f(0)= true | f(n)= not(f(n-1)); fun g(0)= nil | g(n)= 0::g(n-1); fun l(0)= nil | l(n)= n mod 10 :: l(n div 10); fun j(0)= 0 | j(n)= (n mod 10) + j(n div 10);You should find that the call h 20; takes several seconds to evaluate while h 40; takes several weeks - why is this?
map t [1,2,3,4,5,6];
fun t(0) = 0 | t(n) = 2 + t(n-1); fun t 0 = 0 | t n = 2 + t(n-1);