2009/01/24

[scheme][Gauche]append2, reverse, find

プログラミングGauche」P.54 ~ 55

 

  • リストとリストを連結するappend2

;; append list
(define (append2 a b)
  (if (pair? a)
      (cons (car a)(append2 (cdr a) b))
      b))

 


(append2 '(1 2 3) '(4 5 6)) ;; => (1 2 3 4 5 6)
(append2 '(1 (2 3) (4 5 (6))) '(((7 8) 9) 10))
;; => (1 (2 3) (4 5 (6)) ((7 8) 9) 10)

 

 

  • リストを反転させるreverse

;; reverse list
(define (reverse ls)
  (fold cons '() ls))

(reverse '(1 2 3 4 5)) ;; =>  (5 4 3 2 1)

 

;; reverse list 2

(define (reverse2 ls)
  (if (null? (cdr ls))
      ls
      (append2 (reverse2 (cdr ls))(list (car ls)))))

 


(reverse2 '(1 2 3 4 5)) ;; => (5 4 3 2 1)

 

 

 

(define (reverse2 ls)
  (if (null? (cdr ls))
      ls
      (append2 (reverse2 (cdr ls)) (cons (car ls) '()))))

 

 

(reverse2 '(1 2 3 4 5)) ;; => (5 4 3 2 1)

 

 

  • リストから最初に条件に合致した要素を探し出すfind

;; find
(define (find predicate ls)
  (if (null? ls)
      #f
      (if (predicate (car ls))
      (car ls)
      (find predicate (cdr ls)))))

 

 

(find odd? '(1 2 3 4 5)) ;; => 1
(find odd? '(1)) ;; => 1
(find odd? '()) ;; => #f
(find odd? '(2 4 6 8 10)) ;; => #f
(find odd? (cons 1 2)) ;; => 1

 

 

;; find - cond

(define (find predicate ls)
  (cond
   ((null? ls) #f)
   ((predicate (car ls)) (car ls))
   (else (find predicate (cdr ls)))))

 

 

(find even? '(1 2 3 4 5)) ;; => 2
(find even? '(1)) ;; => #f
(find even? '(1 3 5 7)) ;; => #f

 

 

  • リストから条件に合致したすべての要素をリストにして返すfind

(define (find predicate ls)
  (cond
   ((null? ls) '())
   ((predicate (car ls)) (cons (car ls) (find predicate (cdr ls))))
   (else (find predicate (cdr ls)))))

 

 

(find odd? '(1 2 3 4 5 6 7 8 9 10)) ;; => (1 3 5 7 9)
(find even? '(1 2 3 4 5 6 7 8 9 10)) ;; => (2 4 6 8 10)

0 件のコメント:

コメントを投稿