forked from zsszatmari/sfl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImmutableList.h
More file actions
142 lines (118 loc) · 2.34 KB
/
ImmutableList.h
File metadata and controls
142 lines (118 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#ifndef IMMUTABLELIST_H
#define IMMUTABLELIST_H
#include <memory>
namespace sfl
{
/**
* A reference counted list with immutable values. Appending elements to the front of
* the list does not require a copy, which may be beneficial to performance.
*/
template<typename T>
class ImmutableList final
{
private:
struct Node final
{
Node(const T &aValue, const std::shared_ptr<Node> &aNext) :
next(aNext),
value(aValue)
{
}
const std::shared_ptr<Node> next;
const T value;
};
size_t _size;
std::shared_ptr<Node> _node;
ImmutableList(const std::shared_ptr<Node> &node, size_t size) :
_size(size),
_node(node)
{
}
public:
ImmutableList() :
_size(0),
_node(nullptr)
{
}
ImmutableList(const T &t) :
_size(1),
_node(std::make_shared<Node>(t, nullptr))
{
}
size_t size() const
{
return _size;
}
T at(size_t index) const
{
std::shared_ptr<Node> node = _node;
while (index > 0) {
node = node->next;
--index;
}
return node->value;
}
ImmutableList<T> cons(const T& lhs) const
{
return ImmutableList(std::make_shared<Node>(lhs, _node), _size+1);
}
typedef T value_type;
class const_iterator final : public std::iterator<std::forward_iterator_tag,T>
{
public:
const_iterator(const std::shared_ptr<Node> &node, size_t size) :
_size(size),
_node(node)
{
}
bool operator==(const const_iterator &rhs) const
{
return _size == rhs._size;
}
bool operator!=(const const_iterator &rhs) const
{
return _size != rhs._size;
}
const_iterator & operator++()
{
--_size;
_node = _node->next;
return *this;
}
const T& operator*() const
{
return _node->value;
}
const T* operator->() const
{
return &_node->value;
}
private:
size_t _size;
std::shared_ptr<Node> _node;
friend class ImmutableList;
};
const_iterator begin() const
{
return const_iterator(_node, _size);
}
const_iterator end() const
{
return const_iterator(nullptr, 0);
}
};
namespace List
{
template<typename T>
ImmutableList<T> singleton(const T &t)
{
return ImmutableList<T>(t);
}
}
template<typename R, typename T = typename R::value_type>
R cons(const T &lhs, const R &r)
{
return r.cons(lhs);
}
}
#endif