aboutsummaryrefslogtreecommitdiffstats
path: root/csc/list.csc
blob: f42514664952919b02f44a300ba594fba60b10da (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
(define-library (csc list)
  (export
    enumerate
    filter
    intercalate
    revappend
    split-at
    take)
  (import (scheme base)
          (only (csc match)
            match))
  (begin


    (define (take n xs)
      (let loop ((n n)
                 (xs xs)
                 (acc '()))
        (if (or (not (positive? n)) (null? xs))
            (reverse acc)
          (loop (- n 1) (cdr xs) (cons (car xs) acc)))))


    (define (split-at n xs)
      (let loop ((n n)
                 (xs xs)
                 (acc '()))
        (if (or (not (positive? n)) (null? xs))
            (values (reverse acc) xs)
          (loop (- n 1) (cdr xs) (cons (car xs) acc)))))


    (define (revappend a b)
      (let loop ((xs a)
                 (acc b))
        (if (null? xs)
            acc
          (loop (cdr xs) (cons (car xs) acc)))))


    (define (intercalate x l)
      (match l
        ('() '())
        ((_) l)
        ((head . tail) (cons head (cons x (intercalate x tail))))))


    (define (enumerate l)
      (let loop ((i 0)
                 (l l))
        (match l
          ('() '())
          ((head . tail) (cons (cons i head) (loop (+ 1 i) tail))))))


    (define (filter p l)
      (let loop ((l l)
                 (acc '()))
        (match l
          ('() (reverse acc))
          ((x . xs)
           (if (p x)
             (loop xs (cons x acc))
             (loop xs acc))))))))