progs/defs.rec
changeset 626 2d91b2107656
parent 625 6709fa87410b
child 627 f5214da1976e
equal deleted inserted replaced
625:6709fa87410b 626:2d91b2107656
     1 
       
     2 def zero(x) = 0;
       
     3 
       
     4 def suc(x) = x + 1;
       
     5 
       
     6 def pred(x) = if x == 0 then x else x - 1;
       
     7 
       
     8 def add(x, y) = if x == 0 then y else suc(add(x - 1, y));
       
     9 
       
    10 def mult(x, y) = if x == 0 then 0 else add(y, mult(x - 1, y));
       
    11 
       
    12 def pow(x, y) = if y == 0 then 1 else mult(x, pow(x, y - 1));
       
    13 
       
    14 def fib(n) = if n == 0 then 0 
       
    15              else if n == 1 then 1 
       
    16              else fib(n - 1) + fib(n - 2);
       
    17 
       
    18 def fact(n) = if n == 0 then 1 else n * fact(n - 1);
       
    19 
       
    20 def ack(m, n) = if m == 0 then n + 1
       
    21                 else if n == 0 then ack(m - 1, 1)
       
    22                 else ack(m - 1, ack(m, n - 1));
       
    23 
       
    24 def stack_test(x) = x + 1 + 2 + 3 + 4 + 5;
       
    25 
       
    26 def div(x, y) = x / y;   //integer division
       
    27 
       
    28 def rem(x, y) = x % y;   //remainder
       
    29 
       
    30 def gcd(a, b) = if b == 0 then a else gcd(b, a % b);
       
    31 
       
    32 def is_prime_aux(n, i) = 
       
    33   if n % i == 0 then 0
       
    34   else if (i * i) <= n then is_prime_aux(n, i + 1)  
       
    35   else 1;
       
    36 
       
    37 def is_prime(n) = if n == 2 then 1 else is_prime_aux(n, 2);
       
    38 
       
    39 def primes(n) = 
       
    40   if n == 0 then 0
       
    41   else if is_prime(n) == 1 then (write n; primes(n - 1)) 
       
    42   else primes(n - 1);
       
    43 
       
    44 def is_collatz(n) =
       
    45   if n == 1 then 1
       
    46   else if n % 2 == 0 then is_collatz(n / 2)
       
    47   else is_collatz(3 * n + 1);  
       
    48 
       
    49 def collatz_aux(n, i) = 
       
    50   if i > n then 0
       
    51   else if is_collatz(i) == 1 then (write i; collatz_aux(n, i + 1)) 
       
    52   else collatz_aux(n, i + 1);
       
    53 
       
    54 def collatz(n) = collatz_aux(n, 1);
       
    55 
       
    56 def facT(n, acc) = if n == 0 then acc else facT(n - 1, n * acc);
       
    57 
       
    58 
       
    59 //zero(3)
       
    60 //suc(8)
       
    61 //pred(7)
       
    62 //add(3, 4)
       
    63 //mult(4,5)
       
    64 //pow(2, 3)
       
    65 //fib(20)
       
    66 //(write(fact(5)) ; fact(6))
       
    67 //(write(1) ; 2)
       
    68 ack(3, 12)   // for tail-rec test
       
    69 //stack_test(0)
       
    70 //(write (div(11, 3)); rem(11, 3))
       
    71 //gcd(54, 24)
       
    72 //is_prime(2)
       
    73 //primes(1000000)
       
    74 //collatz(5000)
       
    75 //facT(6, 1)
       
    76