Funkcionálne programovanie cvičenie 4

Created: 2009-10-15 - 18:05

;---------------------- symbolicke vyrazy ------------------

(cons 'a '()) ; (a}
(cons 'a (cons 'b ())) ; {a,b}
(cons 'a (cons 'b (cons 'c ()))) ; {a,b,c}

(cons (cons 'a ())
      ()) ; (a)

(cons 1
      (cons (cons 2
                  (cons (cons 3
                              (cons (cons 4
                                          (cons (cons 5
                                                      (cons 6 ()))
                                                ()))
                                    ()))
                        ()))
            ())) ; (1 (2 (3 (4 (5 6)))))

(car '(a b)) ; a
(cadr '(a b)) ; b
(cdr '(a)) ; ()
(car '(a)) ; a
(cddr '(a b)); ()

; vyberanie zo zoznamu

; (a b c)
; car vrati a
; (car (cdr ... )) vrati zvysok ... skratka tejto kombinacie je cadr
; caddr vrati c... je to skratka (car (cdr (cdr)))

; (1 (2 3 (5 7) 9 ))
; postupne chceme vybrat:
; 1 - car
; 2 - caadr
; 3 - cadadr
; 5 - caaddadr
; 7 - cadaddadr
; 9 - cadddadr

; pomocou cons konstruujeme vyrazy
;(lambda (x) (* x x))
;(()(()()))
;(+ (* 3 4)(/ 4 2))
(cons 'lambda
      (cons (cons 'x
                  ())
            (cons (cons '*
                        (cons 'x
                              (cons 'x
                                    ())))
                  ())))
(cons ()
      (cons (cons ()
                  (cons ()
                        ()))
            ()))

;priklad (+ (* 3 4)(/ 4 2))
;oznacim: +    y      z
(cons '+
      (cons (cons '*
                  (cons 3
                        (cons 4
                        ())))
            (cons (cons '/
                        (cons 4
                              (cons 2
                                    ())))
                  ())))

;procedura, ktora najde n-ty prvok zoznamu:
(define (prvok n x)
  (if (= n 1)
      (car x)
      (prvok (- n 1) (cdr x))))

;posledny prvok
(define (posledny x)
  (if (null? (cdr x))
      (car x)
      (posledny (cdr x))))

;dlzka rekurziou
(define (dlzka x)
  (if (null? x)
      0
      (add1 (dlzka (cdr x)))))

;dlzka iterativne
(define (dlzka2 x)
  (define (d x n)
    (if (null? x)
        n
        (d (cdr x) (add1 n))))
  (d x 0))

;spajanie dvoch zoznamov do jedneho
(define (spoj x y)
  (if (null? x)
     y
     (cons (car x)
           (spoj (cdr x)
                 y))))

;posklada zoznam zoznamov do jedneho zoznamu
(define (spoj2 x)
  (if (null? x)
      ()
      (spoj (car x)
            (spoj2 (cdr x)))))

;spoji zoznamy do jedneho zoznamu (teda nemusi byt zoznam zoznamov, ale parametre su '(1 2 3) '(4 5 6) ... atd
(define (spoj3 . x)
  (spoj2 x)
  )

;obratenie zoznamu
(define (obrat x)
  (define (o x y)
    (if (null? x)
        y
        (o (cdr x)
           (cons (car x)
                 y))))
  (o x ()))

;na du: rozdelit zoznam na polovicu...