Add foreach for S-expression lists

Signed-off-by: Leonardo de Moura <leonardo@microsoft.com>
This commit is contained in:
Leonardo de Moura 2013-07-21 14:32:36 -07:00
parent b8315e5593
commit 8af56394cc
2 changed files with 20 additions and 1 deletions

View file

@ -10,6 +10,17 @@ Author: Leonardo de Moura
namespace lean {
template<typename F>
void foreach(sexpr const & l, F f) {
lean_assert(is_list(l));
sexpr const * h = &l;
while (!is_nil(*h)) {
lean_assert(is_cons(*h));
f(head(*h));
h = &tail(*h);
}
}
template<typename F>
sexpr map(sexpr const & l, F f) {
lean_assert(is_list(l));

View file

@ -71,7 +71,7 @@ static void tst1() {
lean_assert(!contains(sexpr{10,20,-2,0,10}, [](sexpr e) { return to_int(e) < -10; }));
}
void tst2() {
static void tst2() {
sexpr a;
a = 2;
lean_assert(a == sexpr(2));
@ -108,9 +108,17 @@ void tst2() {
lean_assert(sexpr(1, 2) == sexpr(1, sexpr(2)));
}
static void tst3() {
int sum = 0;
foreach(sexpr{0, 1, 2, 3, 4},
[&](sexpr const & e) { sum += to_int(e); });
lean_assert(sum == 10);
}
int main() {
continue_on_violation(true);
tst1();
tst2();
tst3();
return has_violations() ? 1 : 0;
}