shithub: mc

Download patch

ref: ab4d1165045bde1fc5b291368e63b0bc0dd7a75d
parent: 03857943018a82e1101cecbb026b5e11f4061dc5
author: Ori Bernstein <ori@eigenstate.org>
date: Sat Feb 6 20:27:46 EST 2016

Add iter utils.

--- a/lib/std/bld.sub
+++ b/lib/std/bld.sub
@@ -33,6 +33,7 @@
 	intparse.myr
 	introspect.myr
 	ipparse.myr
+	iterutil.myr
 	mk.myr
 	mkpath.myr
 	mktemp.myr
--- /dev/null
+++ b/lib/std/iterutil.myr
@@ -1,0 +1,61 @@
+use "types"
+
+pkg std =
+	type zipiter(@a, @b) = struct
+		s1	: @a[:]
+		s2	: @b[:]
+	;;
+
+	type enumiter(@a) = struct
+		s	: @a[:]
+		idx	: size
+	;;
+
+	impl iterable zipiter(@a, @b) -> (@a, @b)
+	impl iterable enumiter(@a) -> (size, @a)
+
+	generic byzip	: (a : @a[:], b : @b[:]	 -> zipiter(@a, @b))
+	generic byenum	: (a : @a[:] -> enumiter(@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 byenum = {a
+	-> [.s = a, .idx = 0]
+}
+
+impl iterable enumiter(@a) -> (size, @b) =
+	__iternext__ = {itp, valp
+		if itp.s.len > itp.idx
+			valp# = (itp.idx, itp.s[itp.idx])
+			itp.idx++
+			-> true
+		else
+			-> false
+		;;
+	}
+
+	__iterfin__ = {itp, valp
+	}
+;;
+
+
--- /dev/null
+++ b/lib/std/test/iterutil.myr
@@ -1,0 +1,19 @@
+use std
+
+const main = {
+	var n
+
+	n = 0
+	for (x, i) in std.byenum([0,2,4,6,8][:])
+		std.assert(x == n, "invalid enum idx")
+		std.assert(i == n*2, "invalid enum val")
+		n++
+	;;
+
+	n = 0
+	for (a, b) in std.byzip([0,2,4,6,8][:], [2,4][:])
+		std.assert(a == n*2, "invalid val from a")
+		std.assert(b == n*2 + 2, "invalid val from b")
+		n++
+	;;
+}