GIML: Tutorial Three: answers

  1. fun t(0)= 0
    |   t(n)= 2+t(n-1);
    
    This function simply doubles its input. To see this by example consider the call t(100).
    t(100) = 2 + t(99)
           = 2 + (2 + t(98))
           = 2 + (2 + (2 + t(97)))
           = ...
           = 2 + 2 + 2 + ... + 2 + 0
           = 200
    
    There will be 100 2's in all
    fun d(0)= "de"
    |   d(n)= "do"^d(n-1)^"da";
    
    Each recursion puts a "do" at the front and a "da" at the end - the base case puts a "de" in the middle. We get a string consisting of n "do"'s a single "de" followed by n "da"'s.
    fun h(0)= 1
    |   h(n)= h(n-1)+h(n-1);
    
    This function returns 2n. Each call effectively doubles the previous value. The function is very slow as the doubling is performed using addition instead of multiplication. In all 2n-1 additions are performed.
    fun m(a,0) = 0
    |   m(a,b) = a+m(a,b-1);
    
    This is the multiplation function. e.g. m(3,5) = 15. The function causes b copies of a to be added to 0. e.g.
    m(5,3) = 5 + m(5,2)
           = 5 + (5 + m(5,1))
           = 5 + (5 + (5 + m(5,0)))
           = 5 + (5 + (5 + 0))
           = 15
    
    fun f(0)= true
    |   f(n)= not(f(n-1));
    
    This function returns true if the input is even and false if it is odd. Follow the logic...
    f(0) = trueZero is an even number
    f(n) = not(f(n-1))The "even-ness" of n is the opposite of the "even-ness" of n-1. That is n is even if n-1 is odd and vis-versa.
    fun g(0)= nil
    |   g(n)= 0::g(n-1);
    
    g returns a list of n 0's. Each call to g conses another 0 onto the list.
    fun l(0)= nil
    |   l(n)= n mod 10 :: l(n div 10);
    
    l returns the decimal digits of its input in reverse order. The value n mod 10 gives the least significant decimal digit of n, The value n div 10 returns the number consisting of the decimal digits of n without the last one. e.g. 1962 mod 10 gives 2. 1962 div 10 gives 196.
    l(1962) = 2 :: l(196)
            = 2 :: (6::l(96))
            = 2 :: (6 :: (9 :: l(1)))
            = 2 :: (6 :: (9 :: (1 :: l(0) )))
            = 2 :: (6 :: (9 :: (1 :: nil )))
            = [2,6,9,1]
    
    fun j(0)= 0
    |   j(n)= (n mod 10) + j(n div 10);
    
    This gives the sum of the decimal digits of n.
  2. See hints and more hints.