util.iterators: Add head() iterator, to return the first n items

Mon, 10 Aug 2009 15:07:32 +0100

author
Matthew Wild <mwild1@gmail.com>
date
Mon, 10 Aug 2009 15:07:32 +0100
changeset 1659
6092fc9b078b
parent 1658
0baa849761b6
child 1660
ae2f60a20428

util.iterators: Add head() iterator, to return the first n items

util/iterators.lua file | annotate | diff | comparison | revisions
--- a/util/iterators.lua	Mon Aug 10 14:29:28 2009 +0100
+++ b/util/iterators.lua	Mon Aug 10 15:07:32 2009 +0100
@@ -78,6 +78,18 @@
 	return x;
 end
 
+-- Return the first n items an iterator returns
+function head(n, f, s, var)
+	local c = 0;
+	return function (s, var)
+		if c >= n then
+			return nil;
+		end
+		c = c + 1;
+		return f(s, var);
+	end, s;
+end
+
 -- Convert the values returned by an iterator to an array
 function it2array(f, s, var)
 	local t, var = {};

mercurial