Prototype (framework JavaScript) ma method zip()
że robi dokładnie to, czego potrzebują. Wiem, że to ci nie pomoże. Zabawne, spodziewałbym się, że Groovy będzie miał coś podobnego, ale nie mogłem znaleźć niczego w klasie Collection
lub List
.
Zresztą, tutaj jest niezbyt ładna realizacja zip()
:
List.metaClass.zip = { List other, Closure cl ->
List result = [];
Iterator left = delegate.iterator();
Iterator right = other.iterator();
while(left.hasNext()&& right.hasNext()){
result.add(
cl.call(left.next(), right.next())
);
}
result;
}
I to jest tutaj w akcji:
def list1 = [1, 1, 1]
def list2 = [1, 1, 1]
print (list1.zip(list2) {it1, it2 -> it1 + it2})
wyjściowa:
[2, 2, 2]
Oczywiście można też zrobić to w mniej typowy sposób, jeśli chcesz, aby rozwiązać swój problem dokładnie (i nie realizuje funkcji rodzajowe pocztowy/MAP):
List.metaClass.addValues = { List other ->
List result = [];
Iterator left = delegate.iterator();
Iterator right = other.iterator();
while(left.hasNext()&& right.hasNext()){
result.add(
left.next() + right.next()
);
}
result;
}
def list1 = [1, 1, 1]
def list2 = [1, 1, 1]
print (list1.addValues(list2))
// Output again: [2, 2, 2]
Możliwe powtórzenie tego pytania: http://stackoverflow.com/questions/4443557/overloading-operator-for-arrays-in-groovy – Northover