feat(util/list): avoid recursion at for_each template
Signed-off-by: Leonardo de Moura <leonardo@microsoft.com>
This commit is contained in:
parent
87775cbc07
commit
d67bf995ed
2 changed files with 23 additions and 5 deletions
|
@ -8,6 +8,7 @@ Author: Leonardo de Moura
|
|||
#include "util/test.h"
|
||||
#include "util/list.h"
|
||||
#include "util/list_fn.h"
|
||||
#include "util/timeit.h"
|
||||
using namespace lean;
|
||||
|
||||
static void tst1() {
|
||||
|
@ -114,6 +115,22 @@ static void tst9(int sz) {
|
|||
std::cout << l3 << "\n";
|
||||
}
|
||||
|
||||
static void tst10(int sz, int num) {
|
||||
list<int> l;
|
||||
for (int i = 0; i < sz; i++) {
|
||||
l = cons(i, l);
|
||||
}
|
||||
{
|
||||
timeit timer(std::cout, "for_each");
|
||||
unsigned sum = 0;
|
||||
for (int i = 0; i < num; i++) {
|
||||
sum = 0;
|
||||
for_each(l, [&](int v) { sum += v; });
|
||||
}
|
||||
std::cout << "sum: " << sum << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
tst1();
|
||||
tst2();
|
||||
|
@ -124,5 +141,6 @@ int main() {
|
|||
tst7();
|
||||
tst8();
|
||||
tst9(100);
|
||||
tst10(1000, 5);
|
||||
return has_violations() ? 1 : 0;
|
||||
}
|
||||
|
|
|
@ -160,11 +160,11 @@ template<typename T, typename F>
|
|||
void for_each(list<T> const & l, F f) {
|
||||
static_assert(std::is_same<typename std::result_of<F(T const &)>::type, void>::value,
|
||||
"for_each: return type of f is not void");
|
||||
if (is_nil(l)) {
|
||||
return;
|
||||
} else {
|
||||
f(head(l));
|
||||
return for_each(tail(l), f);
|
||||
typedef typename list<T>::cell cell;
|
||||
cell * it = l.raw();
|
||||
while (it) {
|
||||
f(it->head());
|
||||
it = it->tail().raw();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue