summaryrefslogtreecommitdiff
path: root/include/erebos/list.h
blob: f5f2d3fb1e6f2280bc8f15beb9774b9e7b2003f3 (plain)
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
#pragma once

#include <functional>
#include <memory>
#include <mutex>
#include <variant>

namespace erebos {

using std::function;
using std::make_shared;
using std::make_unique;
using std::move;
using std::shared_ptr;
using std::unique_ptr;
using std::variant;

template<typename T>
class List
{
public:
	struct Nil { bool operator==(const Nil &) const { return true; } };
	struct Cons {
		T head; List<T> tail;
		bool operator==(const Cons & x) const { return head == x.head && tail == x.tail; }
	};

	List();
	List(const T head, List<T> tail);

	const T & front() const;
	const List & tail() const;

	bool empty() const;

	bool operator==(const List<T> &) const;
	bool operator!=(const List<T> &) const;

	List push_front(T x) const;

private:
	struct Priv;
	shared_ptr<Priv> p;
};

template<typename T>
struct List<T>::Priv
{
	variant<Nil, Cons> value;

	function<void()> eval = {};
	mutable std::once_flag once = {};
};

template<typename T>
List<T>::List():
	p(shared_ptr<Priv>(new Priv { Nil() }))
{
	std::call_once(p->once, [](){});
}

template<typename T>
List<T>::List(T head, List<T> tail):
	p(shared_ptr<Priv>(new Priv {
		Cons { move(head), move(tail) }
	}))
{
	std::call_once(p->once, [](){});
}

template<typename T>
const T & List<T>::front() const
{
	std::call_once(p->once, p->eval);
	return std::get<Cons>(p->value).head;
}

template<typename T>
const List<T> & List<T>::tail() const
{
	std::call_once(p->once, p->eval);
	return std::get<Cons>(p->value).tail;
}

template<typename T>
bool List<T>::empty() const
{
	std::call_once(p->once, p->eval);
	return std::holds_alternative<Nil>(p->value);
}

template<typename T>
bool List<T>::operator==(const List<T> & other) const
{
	if (p == other.p)
		return true;

	std::call_once(p->once, p->eval);
	std::call_once(other.p->once, other.p->eval);
	return p->value == other.p->value;

}

template<typename T>
bool List<T>::operator!=(const List<T> & other) const
{
	return !(*this == other);
}

template<typename T>
List<T> List<T>::push_front(T x) const
{
	return List<T>(move(x), *this);
}

}