Funkcionálne programovanie cvičenie 9

Created: 2009-12-08 - 18:56

(define fib
  (lambda (n)
    (cond ((= n 0) 0)
          ((= n 1) 1)
          (else (+ (fib (- n 1))
                   (fib (- n 2)))))))

(define (memoize f)
  (let ((t (list "fibonacci")))
    (lambda (x)
      (let ((v (pozri x t)))
        (if v v
            (let ((r (f x)))
              (vloz! x r t)
              r))))))

(define memo-fib
  (memoize (lambda (n)
             (cond ((= n 0) 0)
                   ((= n 1) 1)
                   (else (+ (memo-fib (- n 1))
                            (memo-fib (- n 2))))))))

(define (pozri k t)
  (let ((r (assq k (cdr t))))
    (if r (cdr r)
        #f)))

(define (vloz! k v t)
  (let ((r (assq k (cdr t))))
    (if r (set-cdr! r v)
        (set-cdr! t (cons (cons k v)
                          (cdr t))))))

(define (zoznam-permutacii x)
  (if (null? x) '(())
      (vloz-vsade-vo-vsetkych-slovach (car x)
                                      (zoznam-permutacii (cdr x)))))

(define (vloz-vsade-vo-vsetkych-slovach a x)
  (if (null? x) ()
      (append (vloz-vsade a (car x))
              (vloz-vsade-vo-vsetkych-slovach a (cdr x)))))

(define (vloz-vsade a x)
  (if (null? x) (list (list a))
      (cons (cons a x)
            (vloz-prvy (car x)
                       (vloz-vsade a (cdr x))))))

(define (vloz-prvy a x)
  (if (null? x) ()
      (cons (cons a (car x))
            (vloz-prvy a (cdr x)))))

(define (insert-sort x)
  (if (null? x) ()
      (insert (car x)
              (insert-sort (cdr x)))))

(define (insert a x)
  (if (null? x) (list a)
      (if (<= a (car x)) (cons a x)
          (cons (car x) (insert a (cdr x))))))

(define (qsort x)
  (if (null? x) ()
      (let ((a (rozdel (car x) (cdr x))))
        (append (qsort (car a))
                (cons (car x)
                      (qsort (cadr a)))))))

(define (rozdel n x)
  (if (null? x) '(()())
      (let ((a (car x))
            (b (rozdel n (cdr x))))
        (if (< a n)
            (list (cons a (car b))
                  (cadr b))
            (list (car b)
                  (cons a (cadr b)))))))