Skip to content

Commit

Permalink
Skylark: zip function is implemented.
Browse files Browse the repository at this point in the history
--
MOS_MIGRATED_REVID=89296560
  • Loading branch information
Googler authored and hanwen committed Mar 24, 2015
1 parent 7232986 commit c60ec8c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@
import com.google.devtools.build.lib.syntax.SkylarkType;
import com.google.devtools.build.lib.syntax.SkylarkType.SkylarkFunctionType;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand Down Expand Up @@ -950,6 +952,45 @@ public String apply(Object input) {
}
};

@SkylarkBuiltin(name = "zip",
doc = "Returns a <code>list</code> of <code>tuple</code>s, where the i-th tuple contains "
+ "the i-th element from each of the argument sequences or iterables. The list has the "
+ "size of the shortest input. With a single iterable argument, it returns a list of "
+ "1-tuples. With no arguments, it returns an empty list. Examples:"
+ "<pre class=language-python>"
+ "zip() # == []\n"
+ "zip([1, 2]) # == [(1,), (2,)]\n"
+ "zip([1, 2], [3, 4]) # == [(1, 3), (2, 4)]\n"
+ "zip([1, 2], [3, 4, 5]) # == [(1, 3), (2, 4)]</pre>",
returnType = SkylarkList.class)
private static final Function zip = new AbstractFunction("zip") {
@Override
public Object call(List<Object> args, Map<String, Object> kwargs, FuncallExpression ast,
Environment env) throws EvalException, InterruptedException {
Iterator<?>[] iterators = new Iterator<?>[args.size()];
for (int i = 0; i < args.size(); i++) {
iterators[i] = EvalUtils.toIterable(args.get(i), ast.getLocation()).iterator();
}
List<SkylarkList> result = new ArrayList<SkylarkList>();
boolean allHasNext;
do {
allHasNext = !args.isEmpty();
List<Object> elem = Lists.newArrayListWithExpectedSize(args.size());
for (Iterator<?> iterator : iterators) {
if (iterator.hasNext()) {
elem.add(iterator.next());
} else {
allHasNext = false;
}
}
if (allHasNext) {
result.add(SkylarkList.tuple(elem));
}
} while (allHasNext);
return SkylarkList.list(result, ast.getLocation());
}
};

/**
* Skylark String module.
*/
Expand Down Expand Up @@ -1052,6 +1093,7 @@ public static final class DictModule {}
.put(type, SkylarkType.of(String.class))
.put(fail, SkylarkType.NONE)
.put(print, SkylarkType.NONE)
.put(zip, SkylarkType.LIST)
.build();

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public List<Object> toList() {

@Override
public String toString() {
return "[]";
return isTuple() ? "()" : "[]";
}
}

Expand Down

0 comments on commit c60ec8c

Please sign in to comment.