~jojo/Carth

ref: b29388e4750e873406e37b50605ac0ea6d24225c Carth/std/array.carth -rw-r--r-- 676 bytes
b29388e4JoJo Make (i8*) the generic ptr type instead of ({}*) 1 year, 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
(import iter)
(import mem)

(define: (array/iter (Array ptr len))
    (forall (a) (Fun (Array a) (Iter a)))
  (map (<o deref (<o (ptr/+ ptr) cast))
       (xrange 0 (cast len))))

(define: (array/collect xs) (forall (a) (Fun (Iter a) (Array a)))
  (let ((n (iter/length xs))
        (ptr (: (transmute (id@"GC_malloc" (* (sizeof a) n))) (Box a))))
    (foldl (fun (v (Pair i x)) (array/insert i x v))
           (Array ptr (cast n))
           (enumerate xs))))

(define: (array/insert i x (Array ptr n))
    (forall (a) (Fun Nat a (Array a) (Array a)))
  (if (>= i n)
      (panic "array/insert after end of array")
    (seq (store x (ptr/+ ptr i))
         (Array ptr n))))