forked from seven1m/30-days-of-elixir
-
Notifications
You must be signed in to change notification settings - Fork 1
/
29-vector.exs
302 lines (258 loc) · 7.53 KB
/
29-vector.exs
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
defmodule Vector do
@moduledoc """
This is my (woefully inadequate) attempt at building a Vector with constant-time
lookup using a Hash Array Mapped Trie (HAMT).
While it is blazing fast for getting the value at an index,
it's way slower (than just using a list) in the case of adding values and iterating.
Another shortcoming is the hash function will certainly create collisions and
I didn't bother to account for that in the storage. Sorry :-(
And last, the tree structure isn't compressed, so it gets big fast... don't bother
trying to IO.inspect the sucker!
But this is good enough for a single day's excercise, and I learned a ton
in the process... Yay for learning! :-)
"""
@template :erlang.make_tuple(10, nil)
require Record
Record.defrecordp :vec, Vector, size: 0, children: {nil, @template}
@doc """
Builds a new empty vector.
iex> Vector.new
{Vector, 0, {nil, {nil, nil, nil, nil, nil, nil, nil, nil, nil, nil}}}
"""
def new do
vec()
end
@doc """
Builds a new vector from the given list.
iex> v = Vector.new(["tim", "jen", "mac", "kai"])
iex> Vector.size(v)
4
iex> Vector.get(v, 1)
"jen"
"""
def new(list) do
from_list(list, new)
end
@doc """
Builds a new vector with count items initialized to given value
iex> v = Vector.new(4, "foo")
iex> Vector.size(v)
4
iex> Vector.get(v, 3)
"foo"
"""
def new(count, val) do
Enum.reduce 0..(count-1), new, fn i, v ->
Vector.put(v, i, val)
end
end
@doc """
Get the size of the vector.
"""
def size(vec(size: size)) do
size
end
@doc """
Gets the value from the vector at the given index.
iex> v = Vector.put(nil, 10, "tim")
iex> Vector.get(v, 10)
"tim"
"""
def get(vec(children: children), index) do
do_get(children, hash(index))
end
@doc """
Puts the value in a vector at the given index.
iex> v = Vector.new
iex> v = Vector.put(v, 10, "tim")
iex> Vector.get(v, 10)
"tim"
"""
def put(v = vec(size: size, children: children), index, value) do
children = do_put(children, hash(index), value)
if index >= size do
vec(size: index + 1, children: children)
else
v
end
end
def put(nil, index, value), do: put(new, index, value)
@doc """
Given a vector, an accumulator, and a function, iterate over
each item in the vector passing the item and the accumulator
to the function. The function should return the modified
accumulator.
iex> v = Vector.new([1,2,3])
iex> Vector.reduce(v, 0, &(&2 + &1))
6
"""
def reduce(v = vec(size: size), acc, fun) do
Enum.reduce 0..(size-1), acc, fn index, acc ->
fun.(get(v, index), acc)
end
end
def find(v = vec(size: size), value, index \\ 0) do
cond do
index >= size -> nil
get(v, index) == value -> index
true -> find(v, value, index+1)
end
end
def from_list(list, v), do: from_list(list, v, 0)
def from_list([val | rest], v, index) do
v = put(v, index, val)
from_list(rest, v, index+1)
end
def from_list([], v, _), do: v
# traversed down to a non-existent key
defp do_get(nil, _) do
nil
end
# at the last node of our tree, so we should have a value!
defp do_get({val, _}, []) do
val
end
# traverse down the tree to get the value
defp do_get({_, children}, [pos | hash_rest]) do
node = elem(children, pos)
do_get(node, hash_rest)
end
# at the last leaf of our branch, so store the value
# FIXME our hash function will have collisions, so we really should
# store duplicates properly here, but we don't yet
defp do_put(_, [], value) do
{value, @template}
end
# build a new branch
defp do_put(nil, hash, value) do
do_put({nil, @template}, hash, value)
end
# traverse down the tree to store the value
defp do_put({val, children}, [pos | hash_rest], value) do
tree = do_put(elem(children, pos), hash_rest, value)
{val, put_elem(children, pos, tree)}
end
# generate a hash of the index,
# i.e. a list of positions for each level of depth in the tree
defp hash(index) do
chars = index
|> :erlang.phash2
|> Integer.to_char_list
for c <- chars, do: List.to_integer([c])
end
end
defimpl Enumerable, for: Vector do
def count(v) do
{:ok, Vector.size(v)}
end
# FIXME this is broke
def reduce(v, acc, fun) do
Vector.reduce(v, acc, fun)
end
def member?(v, val) do
{:ok, Vector.index(v, val) != nil}
end
end
ExUnit.start
defmodule VectorTest do
use ExUnit.Case
test "stores a value at an index in a tree structure" do
v = Vector.new
v = Vector.put(v, 0, "tim")
assert v == {Vector, 1, {nil, {
nil, nil, nil, nil, nil, nil, nil, nil,
{nil, {
nil, nil, nil, nil, nil, nil, nil, nil,
{nil, {
nil, nil, nil, nil, nil, nil, nil,
{nil, {
nil, nil,
{nil, {
nil, nil, nil,
{nil, {
nil, nil, nil, nil, nil, nil, nil,
{nil, {
nil, nil,
{nil, {
nil, nil, nil, nil, nil,
{"tim", {nil, nil, nil, nil, nil, nil, nil, nil, nil, nil}},
nil, nil, nil, nil}},
nil, nil, nil, nil, nil, nil, nil}},
nil, nil}},
nil, nil, nil, nil, nil, nil}},
nil, nil, nil, nil, nil, nil, nil}},
nil, nil}},
nil}},
nil}}}
end
test "size" do
v = Vector.new
v = Vector.put(v, 0, "tim")
v = Vector.put(v, 1, "jen")
assert Vector.size(v) == 2
v = Vector.put(v, 9, "mac")
assert Vector.size(v) == 10
end
test "get" do
v = Vector.new
v = Vector.put(v, 0, "tim")
v = Vector.put(v, 1, "jen")
v = Vector.put(v, 2, "mac")
assert Vector.get(v, 0) == "tim"
assert Vector.get(v, 1) == "jen"
assert Vector.get(v, 2) == "mac"
end
test "get non-existent key" do
v = Vector.new
assert Vector.get(v, 10) == nil
end
test "count" do
v = Vector.new([1,2,3])
assert tuple_size(v) == 3
end
test "reduce" do
v = Vector.new([1,2,3])
sum = Vector.reduce(v, 0, &(&1 + &2))
assert sum == 6
end
test "find" do
v = Vector.new([1,2,3])
index = Vector.find(v, 3)
assert index == 2
end
@size 100_000
test "creation speed" do
{microsecs, _} = :timer.tc fn ->
List.duplicate("foo", @size)
end
IO.puts "List creation took #{microsecs} microsecs" # 3,525 microsecs
{microsecs, _} = :timer.tc fn ->
Vector.new(@size, "foo")
end
IO.puts "Vector creation took #{microsecs} microsecs" # 265,647 microsecs
end
test "iteration speed" do
list = List.duplicate("foo", @size)
{microsecs, _} = :timer.tc fn ->
Enum.reduce list, 0, fn _, count -> count + 1 end
end
IO.puts "List traversal took #{microsecs} microsecs" # 1605 microsecs
vector = Vector.new(@size, "foo")
{microsecs, _} = :timer.tc fn ->
Vector.reduce vector, 0, fn _, count -> count + 1 end
end
IO.puts "Vector traversal took #{microsecs} microsecs" # 105,732 microsecs
end
test "access speed" do
list = List.duplicate("foo", @size)
{microsecs, _} = :timer.tc fn ->
assert Enum.at(list, @size-1) == "foo"
end
IO.puts "List access took #{microsecs} microsecs" # 997 microsecs
vector = Vector.new(@size, "foo")
{microsecs, _} = :timer.tc fn ->
assert Vector.get(vector, @size-1) == "foo"
end
IO.puts "Vector access took #{microsecs} microsecs" # 3 microsecs
end
end