プログラミングGauche
p.56 listの長さを計算する
#!/usr/bin/env gosh (define (length lis) (define (length-walk lis n) (if (null? lis) n (length-walk (cdr lis) (+ n 1)) ) ) (length-walk lis 0)) (print (length '(1 2 3)))
p.56 リスト内から条件を満たす要素を抜き出したリストを返す
#!/usr/bin/env gosh (define (find pred lis) (if (null? lis) #f (if (pred (car lis)) (car lis) (find pred (cdr lis)) ) )) (print (find odd? '(2 3 4 5))) (print (find (lambda (i) (if (and (> i 2) (odd? i)) #t #f)) '(1 2 3 4)))
3 3
(define (filter pred lis) (define (filter-each pred lis res) (if (null? lis) res (if (pred (car lis)) (filter-each pred (cdr lis) (append res (list(car lis)))) (filter-each pred (cdr lis) res) ) ) ) (filter-each pred lis '())) (define data '(2 3 4 5 10 11 34 35 1 2 3)) (print data) (print (filter odd? data))
(2 3 4 5 10 11 34 35 1 2 3) (3 5 11 35 1 3)
(define data '(4 10 11 50 "hello work" 5 8)) (print data) (print (filter (lambda (x) (if (and (number? x) (odd? x)) #t #f)) data))
(4 10 11 50 hello work 5 8) (11 5)