/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #pragma once #include #include "util/lazy_list.h" #include "util/list.h" namespace lean { template void for_each(lazy_list l, F && f) { while (true) { auto p = l.pull(); if (p) { f(p->first); l = p->second; } else { break; } } } template lazy_list take(unsigned sz, lazy_list const & l) { if (sz == 0) { return lazy_list(); } else { return lazy_list([=]() { auto p = l.pull(); if (p) return some(mk_pair(p->first, take(sz - 1, p->second))); else return p; }); } } template lazy_list to_lazy(list l) { if (l) { return lazy_list([=]() { return some(mk_pair(head(l), to_lazy(tail(l)))); }); } else { return lazy_list(); } } template lazy_list append(lazy_list const & l1, lazy_list const & l2) { return lazy_list([=]() { auto p = l1.pull(); if (!p) return l2.pull(); else return some(mk_pair(p->first, append(p->second, l2))); }); } template lazy_list orelse(lazy_list const & l1, lazy_list const & l2) { return lazy_list([=]() { auto p = l1.pull(); if (!p) return l2.pull(); else return some(mk_pair(p->first, orelse(p->second, lazy_list()))); }); } template lazy_list interleave(lazy_list const & l1, lazy_list const & l2) { return lazy_list([=]() { auto p = l1.pull(); if (!p) return l2.pull(); else return some(mk_pair(p->first, interleave(l2, p->second))); }); } template lazy_list map(lazy_list const & l, F && f) { return lazy_list([=]() { auto p = l.pull(); if (!p) return p; else return some(mk_pair(f(p->first), map(p->second, f))); }); } template lazy_list filter(lazy_list const & l, P && pred) { return lazy_list([=]() { auto p = l.pull(); if (!p) return p; else if (pred(p->first)) return some(mk_pair(p->first, p->second)); else return filter(p->second, pred).pull(); }); } template lazy_list map_append_aux(lazy_list const & h, lazy_list const & l, F && f) { return lazy_list([=]() { auto p1 = h.pull(); if (p1) { return some(mk_pair(p1->first, map_append_aux(p1->second, l, f))); } else { auto p2 = l.pull(); if (p2) { return map_append_aux(f(p2->first), p2->second, f).pull(); } else { return typename lazy_list::maybe_pair(); } } }); } template lazy_list map_append(lazy_list const & l, F && f) { return map_append_aux(lazy_list(), l, f); } }