-
Notifications
You must be signed in to change notification settings - Fork 1
/
ici-core4.ici
90 lines (82 loc) · 2.17 KB
/
ici-core4.ici
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* apply(o, fn [, args...])
*
* Call a function on each element of an aggregate.
*
* If the aggregate is an array, set or string the
* function is called for each member of the object
* in sequence. The argument being called with the
* n'th element as its first argument and any extra
* arguments passed to apply() following that.
*
* If the aggregate is a map the function is called
* with two arguments, the key and value objects from
* the map for the current element being traversed.
* Map traversal is shallow but does visit any
* super map.
*/
extern apply(fn, aggr) {
var vargs = [array];
k := v := NULL;
switch (t := typeof(aggr))
{
case "array":
case "set":
case "string":
forall (v in aggr)
call(fn, array(v) + vargs);
break;
case "map":
if (super(aggr))
call(apply, array(super(aggr), fn) + vargs);
forall (v, k in aggr)
call(fn, array(k, v) + vargs);
break;
default:
fail(sprintf("cannot apply a function to a %s", t));
}
}
/*
* aggr = transform(aggr, fn [, args...])
*
* Transforms an aggregate by passing each element through a function and returning
* a new aggregate, of the same type as that being transformed, containing the
* transformed elements.
*
* i.e. m' = transform(m, f)
*
* Return m' by transforming the elements of m through f().
*/
extern transform(aggr, fn) {
var vargs = [array];
v := k := r := NULL;
switch (t := typeof(aggr))
{
case "array":
r := array();
forall (v in aggr)
push(r, call(fn, array(v) + vargs));
break;
case "set":
r := set();
forall (v in aggr)
r[call(fn, array(v) + vargs)] := 1;
break;
case "string":
r := array();
forall (v in aggr)
push(r, call(fn, array(v) + vargs));
r := implode(r);
break;
case "map":
r := map();
if (super(aggr))
super(r, call(map, array(super(aggr), fn) + vargs));
forall (v, k in aggr)
r[k] := call(fn, array(v, k) + vargs);
break;
default:
fail(sprintf("cannot map a %s", t));
}
return r;
}