Guest User

(Ocaml-like) Discriminated Unions / Tagged Unions

a guest
Oct 25th, 2020
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <iostream>
  2. #include <variant>
  3. #include <vector>
  4. #include <map>
  5. #include <algorithm>
  6. #include <iterator>
  7.  
  8. const auto usdEurCourse = 1.19;
  9. const auto usdBtcCourse = 0.000076;
  10.  
  11. typedef std::tuple<std::string, double> AnotherTuple;
  12.  
  13. typedef std::variant<
  14.     /*USD*/ double,
  15.     /*EUR*/ double,
  16.     /*BTC*/ double,
  17.     /*Another*/ AnotherTuple
  18. > currency;
  19.  
  20. enum
  21. {
  22.     USD,
  23.     EUR,
  24.     BTC,
  25.     Another
  26. };
  27.  
  28. auto comodityMarketsValues = std::map<std::string, currency>{
  29.     { "Gold", currency{ std::in_place_index<USD>, 5.75 } },
  30.     { "Platinium DAX", currency{ std::in_place_index<EUR>, 5.23 } },
  31.     { "FSTE Oil", currency{ std::in_place_index<Another>, AnotherTuple{ "GBP", 1023.22 } } },
  32. };
  33.  
  34. double toUSD(currency curr)
  35. {
  36.     switch (curr.index())
  37.     {
  38.     case USD: return std::get<USD>(curr);
  39.     case EUR: return std::get<EUR>(curr) * usdEurCourse;
  40.     case BTC: return std::get<BTC>(curr) * usdBtcCourse;
  41.     default: throw std::runtime_error("Unsupported currency");
  42.     }
  43. }
  44.  
  45. int main()
  46. {
  47.     std::map<std::string, currency> comodityMarketsValuesInUSD;
  48.  
  49.     std::transform(
  50.         comodityMarketsValues.begin(),
  51.         comodityMarketsValues.end(),
  52.         std::inserter(comodityMarketsValuesInUSD, comodityMarketsValuesInUSD.begin()),
  53.         [](std::pair<std::string, currency> nameCurrPair) -> std::pair<std::string, currency>
  54.         {
  55.             return std::pair<std::string, currency>(
  56.                 nameCurrPair.first,
  57.                 currency{ std::in_place_index<USD>, toUSD(nameCurrPair.second) }
  58.             );
  59.         }
  60.     );
  61. }
Advertisement
Add Comment
Please, Sign In to add comment