Friday, August 31, 2007

Iteration vs Recursion, Lisp vs C++, Functions vs Templates



1st chapter of SICP book task: recursive process in Scheme programming language without any loop forms (like for-each).

Implementation in Scheme:

;; recursive process
;; 1.11 from sicp
(define (f_rec1_11 n)
( cond ((< n 3) n )
(else (+
(f_rec1_11 (- n 1))
(f_rec1_11 (- n 2))
(f_rec1_11 (- n 3))))))

;; iterative (tail recursion)
(define (f_iter1_11 n) (f_i 0 1 2 (- n 2) ))

(define (f_i a0 a1 a2 count)
(if (= count 0) a2
(f_i a1 a2 (+ a0 a1 a2) (- count 1))))


Task in C: To implement without for, while, do, until, and goto output of numbers from one to 1000 in C.

#include <stdio.h>

int print_next_up(int in,int up)
{
printf("%d\n\n", ++in);
if (in >= up) return 0;
print_next_up(in,up);
}

int main()
{
print_next_up(0,1000);
return 0;
}


Example of the work of the C++ preprocessor:
Procedure in C++, printing numbers from 10 to 1 without even passing values to method calls or constructors. And recursion is in preprocessor.

#include <iostream>

template <int n> class printer
{
public :
printer() {
fun();
}
private:
int fun ()
{
std::cout << n << std::endl;
printer <n-1> myprinter;
}
};


template<> class printer<0>
{};

int main()
{
printer<10> a;
return 0;
}


And last, implementation of the task without loop constructs and recursion.

#include <iostream>

class my{
public:
static int a;
my()
{ std::cout << ++a << std::endl; }
};

int my::a = 0;

int main()
{
my myj[1000];
}

No comments: