Skip to content

Add a lazyt class for delaying computations #5090

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 9, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions unit/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ SRC += analyses/ai/ai.cpp \
util/irep_sharing.cpp \
util/json_array.cpp \
util/json_object.cpp \
util/lazy.cpp \
util/memory_info.cpp \
util/message.cpp \
util/optional.cpp \
Expand Down
29 changes: 29 additions & 0 deletions unit/util/lazy.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*******************************************************************\

Module: Unit tests for lazy

Author: Romain Brenguier, [email protected]

\*******************************************************************/

#include <testing-utils/use_catch.h>
#include <util/lazy.h>

SCENARIO("lazy test", "[core][util][lazy]")
{
std::size_t call_counter = 0;
auto length_with_counter = [&call_counter](const std::string &s) {
++call_counter;
return s.length();
};
auto lazy_length =
lazyt<int>::from_fun([&]() { return length_with_counter("foo"); });
Copy link
Contributor

@LAJW LAJW Sep 6, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😊 https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/lazy-expressions
And now you could even infer return type by doing:

template<T> auto lazy(T func) -> lazyt<decltype(func())> { ... }

Also, () in zero-argument lambdas is optional.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm adding it in a follow-up PR: #5101


REQUIRE(call_counter == 0);
auto result = lazy_length.force();
REQUIRE(call_counter == 1);
REQUIRE(result == 3);
result = lazy_length.force();
REQUIRE(call_counter == 1);
REQUIRE(result == 3);
}