#lang racket (require (lib "trace.ss")) ; ------------------Recursivitate pe stivă------------------ (define (fact-stack n) (if (zero? n) 1 (* n (fact-stack (- n 1))))) ;(trace fact-stack) ;(fact-stack 4) ; ------------------Recursivitate pe coadă------------------ (define (fact-tail n) (fact-tail-helper n 1)) (define (fact-tail-helper n acc) (if (zero? n) acc (fact-tail-helper (- n 1) (* n acc)))) (trace fact-tail-helper) (fact-tail 10) ; ------------------Recursivitate arborescentă------------------ (define (fibo-stack n) (if (< n 2) n (+ (fibo-stack (- n 1)) (fibo-stack (- n 2))))) ;(trace fibo-stack) ;(fibo-stack 5) ;(fibo-stack 40) ;; deja incepe sa dureze mult (define (fibo-tail n) (fibo-tail-helper n 0 1)) (define (fibo-tail-helper n a b) (if (zero? n) a (fibo-tail-helper (sub1 n) b (+ a b)))) ; fibo(0) = 0, fibo(1) = 1 ;(trace fibo-tail-helper) ;(fibo-tail 5) ;(helper 5 0 1) ;(helper 4 1 1) ;(helper 3 1 2) ;(helper 2 2 3) ;(helper 1 3 5) ;(helper 0 5 8) ;0 1 1 2 3 5 ;(map fibo-tail '(0 1 2 3 4 5 6 7)) ;(fibo-tail 100000) ; ------------------Recunoaștere tip de recursivitate------------------ (define (g L result) (cond ((null? L) result) ((list? (car L)) (g (cdr L) (append (g (car L) '()) result))) ; evaluare aplicativă (else (g (cdr L) (cons (car L) result))))) (trace g) (g '(1 2 (3 4) (5 (6 7))) '())