Skip to content

Instantly share code, notes, and snippets.

@rsalgado
Created August 30, 2019 01:41
Show Gist options
  • Save rsalgado/2e1ee527d040dd4e8657bf49590f6063 to your computer and use it in GitHub Desktop.
Save rsalgado/2e1ee527d040dd4e8657bf49590f6063 to your computer and use it in GitHub Desktop.
Small Elixir Wrapper of Erlang Arrays
defmodule ArrayWrapper do
@behaviour Access
defstruct erlang_array: :array.new()
@impl Access
def fetch(%ArrayWrapper{erlang_array: array}, key)
when is_integer(key) and (key >= 0) do
case :array.get(key, array) do
:undefined -> :error
value -> {:ok, value}
end
end
@impl Access
def get_and_update(%ArrayWrapper{erlang_array: array} = wrapper, key, func)
when is_integer(key) and (key >= 0) do
value = wrapper[key] # Fetch the value
case func.(value) do
{get_value, update_value} ->
wrapper = %{wrapper | erlang_array: :array.set(key, update_value, array)}
# Return the get value and the struct with the updated array
{get_value, wrapper}
:pop ->
wrapper = %{wrapper | erlang_array: :array.reset(key, array)}
# Return the value and the struct with the updated array (without entry)
{value, wrapper}
end
end
@impl Access
def pop(%ArrayWrapper{erlang_array: array} = wrapper, key)
when is_integer(key) and (key >= 0) do
value = wrapper[key]
wrapper = %{wrapper | erlang_array: :array.reset(key, array)}
# Return the value and the struct with the updated array (without entry)
{value, wrapper}
end
def to_list(%ArrayWrapper{erlang_array: array}) do
:array.to_list(array)
end
def size(%ArrayWrapper{erlang_array: array}) do
:array.size(array)
end
defimpl Inspect, for: ArrayWrapper do
import Inspect.Algebra
def inspect(array_wrapper, opts) do
concat(["#ArrayWrapper<", to_doc(ArrayWrapper.to_list(array_wrapper), opts), ">"])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment