dictionary.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef EXECUTABLE_SEMANTICS_INTERPRETER_DICTIONARY_H_
  5. #define EXECUTABLE_SEMANTICS_INTERPRETER_DICTIONARY_H_
  6. #include <iostream>
  7. #include <list>
  8. #include <optional>
  9. #include <string>
  10. #include "executable_semantics/interpreter/list_node.h"
  11. namespace Carbon {
  12. // A persistent dictionary with a simple implementation.
  13. // Copying the dictionary is O(1) time.
  14. template <class K, class V>
  15. class Dictionary {
  16. public:
  17. // Create an empty dictionary.
  18. Dictionary() { head = nullptr; }
  19. // Return the value associated with the given key.
  20. // Time complexity: O(n) where n is the number of times
  21. // any value has been set across all keys.
  22. auto Get(const K& key) -> std::optional<V> {
  23. for (auto kv : *this) {
  24. if (kv.first == key) {
  25. return kv.second;
  26. }
  27. }
  28. return std::nullopt;
  29. }
  30. // Associate the value v with key k in the dictionary.
  31. // Time complexity: O(1).
  32. auto Set(const K& k, const V& v) -> void {
  33. head = new ListNode<std::pair<K, V>>(std::make_pair(k, v), head);
  34. }
  35. typedef ListNodeIterator<std::pair<K, V>> Iterator;
  36. // The position of the first element of the dictionary
  37. // or `end()` if the dictionary is empty.
  38. auto begin() const -> Iterator { return Iterator(head); }
  39. // The position one past that of the last element.
  40. auto end() const -> Iterator { return Iterator(nullptr); }
  41. private:
  42. Dictionary(ListNode<std::pair<K, V>>* h) : head(h) {}
  43. ListNode<std::pair<K, V>>* head;
  44. };
  45. } // namespace Carbon
  46. #endif // EXECUTABLE_SEMANTICS_INTERPRETER_DICTIONARY_H_