lists.scm 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. (define (length l)
  2. (let loop ((l l) (len 0))
  3. (if (null? l) len (loop (cdr l) (+ len 1)))))
  4. (define (map f l)
  5. (if (null? l)
  6. '()
  7. (cons (f (car l))
  8. (map f (cdr l)))))
  9. (define (for-each proc l)
  10. (if (null? l)
  11. #t
  12. (begin (proc (car l))
  13. (for-each proc (cdr l)))))
  14. (define (foldl f a xs)
  15. (if (null? xs)
  16. a
  17. (foldl f (f a (car xs)) (cdr xs))))
  18. (define (append x y)
  19. (if (null? x)
  20. y
  21. (cons (car x) (append (cdr x) y))))
  22. (define (revappend l r)
  23. (if (null? l)
  24. r
  25. (revappend (cdr l) (cons (car l) r))))
  26. (define (reverse l) (revappend l '()))
  27. (define (filter p l)
  28. (if (null? l)
  29. '()
  30. (if (p (car l))
  31. (cons (car l) (filter p (cdr l)))
  32. (filter p (cdr l)))))
  33. (define (concat-map func lst)
  34. (if (null? lst)
  35. '()
  36. (append (func (car lst))
  37. (concat-map func (cdr lst)))))
  38. (define (concatenate lists) (concat-map (lambda (i) i) lists))
  39. (define (member elt lst)
  40. (if (null? lst) #f (or (eq? elt (car lst)) (member elt (cdr lst)))))
  41. (define (copy-list l) (map (lambda (i) i) l))
  42. (define (fold kons knil lst)
  43. (if (null? lst)
  44. knil
  45. (kons (car lst)
  46. (fold kons knil (cdr lst)))))
  47. (define (index nm lst)
  48. (let loop ((i 0) (lst lst))
  49. (if (null? lst)
  50. #f
  51. (if (eq? nm (car lst))
  52. i
  53. (loop (+ i 1) (cdr lst))))))