Reaktoro
A unified framework for modeling chemically reactive systems
OptimizationUtils.hpp
1 // Reaktoro is a unified framework for modeling chemically reactive systems.
2 //
3 // Copyright (C) 2014-2018 Allan Leal
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public License
16 // along with this library. If not, see <http://www.gnu.org/licenses/>.
17 
18 #pragma once
19 
20 // C++ includes
21 #include <functional>
22 #include <map>
23 #include <memory>
24 #include <tuple>
25 
26 namespace Reaktoro {
27 
28 template <typename Ret, typename... Args>
29 auto memoize(std::function<Ret(Args...)> f) -> std::function<Ret(Args...)>
30 {
31  auto cache = std::make_shared<std::map<std::tuple<Args...>, Ret>>();
32  return [=](Args... args) mutable -> Ret
33  {
34  std::tuple<Args...> t(args...);
35  if(cache->find(t) == cache->end())
36  (*cache)[t] = f(args...);
37  return (*cache)[t];
38  };
39 }
40 
41 template<typename Ret, typename... Args>
42 auto memoizeLast(std::function<Ret(Args...)> f) -> std::function<Ret(Args...)>
43 {
44  std::tuple<typename std::decay<Args>::type...> cache;
45  Ret result = Ret();
46  return [=](Args... args) mutable -> Ret
47  {
48  if(std::tie(args...) == cache)
49  return Ret(result);
50  cache = std::make_tuple(args...);
51  return result = f(args...);
52  };
53 }
54 
55 template<typename Ret, typename... Args>
56 auto memoizeLastPtr(std::function<Ret(Args...)> f) -> std::shared_ptr<std::function<Ret(Args...)>>
57 {
58  return std::make_shared<std::function<Ret(Args...)>>(memoizeLast(f));
59 }
60 
61 template<typename Ret, typename... Args>
62 auto dereference(const std::shared_ptr<std::function<Ret(Args...)>>& f) -> std::function<Ret(Args...)>
63 {
64  return [=](Args... args) -> Ret { return (*f)(args...); };
65 }
66 
67 } // namespace Reaktoro
68 
The namespace containing all components of the Reaktoro library.
Definition: ChemicalScalar.hpp:24