summaryrefslogtreecommitdiff
path: root/lib/std/iterutil.myr
blob: 79b0e80fb572231ee17060e1bcc8cb2e849e52d7 (plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use "types"
use "fmt"
use "extremum"

pkg std =
	type zipiter(@a, @b) = struct
		s1	: @a[:]
		s2	: @b[:]
	;;

	type reverseiter(@a) = struct
		sl	: @a[:]
		idx	: size
	;;

	type enumiter(@a) = struct
		idx	: size
		sl	: @a[:]
	;;

	type refiter(@a) = struct
		idx	: size
		sl	: @a[:]
	;;

	type chunkiter(@a) = struct
		idx	: size
		blksz	: size
		sl	: @a[:]
	;;

	impl iterable zipiter(@a, @b) -> (@a, @b)
	impl iterable enumiter(@a) -> (size, @a)
	impl iterable reverseiter(@a) -> @a
	impl iterable refiter(@a) -> @a#
	impl iterable chunkiter(@a) -> @a[:]

	generic byzip	: (a : @a[:], b : @b[:]	 -> zipiter(@a, @b))
	generic byenum	: (a : @a[:] -> enumiter(@a))
	generic byreverse 	: (sl : @a[:] -> reverseiter(@a))
	generic byref 	: (sl : @a[:] -> refiter(@a))
	generic bychunk	: (a : @a[:], chunk : size -> chunkiter(@a))
;;

generic byzip = {a, b
	-> [.s1 = a, .s2 = b]
}

impl iterable zipiter(@a, @b) -> (@a, @b) =
	__iternext__ = {itp, valp
		if itp.s1.len > 0 && itp.s2.len > 0
			valp# = (itp.s1[0], itp.s2[0])
			itp.s1 = itp.s1[1:]
			itp.s2 = itp.s2[1:]
			-> true
		else
			-> false
		;;
	}

	__iterfin__ = {itp, valp
	}
;;

generic byreverse = {sl
	-> [.sl = sl, .idx = sl.len]
}

impl iterable reverseiter(@a) -> @a =
	__iternext__ = {itp, valp
		if itp.idx > 0
			valp# = itp.sl[itp.idx - 1]
			itp.idx--
			-> true
		else
			-> false
		;;
	}

	__iterfin__ = {itp, valp
	}
;;

generic byenum = {a
	-> [.sl = a, .idx = 0]
}

impl iterable enumiter(@a) -> (size, @a) =
	__iternext__ = {itp, valp
		if itp.idx == itp.sl.len
			-> false
		;;
		valp# = (itp.idx, itp.sl[itp.idx])
		itp.idx++
		-> true
	}

	__iterfin__ = {itp, valp
	}
;;

generic byref = {a
	-> [.sl = a, .idx = 0]
}

impl iterable refiter(@a) -> @a# =
	__iternext__ = {itp, valp
		if itp.idx == itp.sl.len
			-> false
		;;
		valp# = &itp.sl[itp.idx]
		itp.idx++
		-> true
	}

	__iterfin__ = {itp, valp
	}
;;

generic bychunk = {a, sz
	-> [.sl = a, .idx = 0, .blksz = sz]
}

impl iterable chunkiter(@a) -> @a[:] =
	__iternext__ = {itp, valp
		var len

		len = min(itp.blksz, itp.sl.len - itp.idx)
		if itp.idx + len == itp.sl.len
			-> false
		;;
		valp# = itp.sl[itp.idx: itp.idx + len]
		itp.idx += itp.blksz
		-> true
	}

	__iterfin__ = {itp, valp
	}
;;