Skip to content

Instantly share code, notes, and snippets.

@brweber2
Last active April 4, 2022 03:38
Show Gist options
  • Save brweber2/b724969b5d1d35443e6c to your computer and use it in GitHub Desktop.
Save brweber2/b724969b5d1d35443e6c to your computer and use it in GitHub Desktop.
Elixir Enumerable for binaries....
defmodule Benum do
defimpl Enumerable, for: BitString do
def count(collection) when is_binary(collection) do
{:ok, Enum.reduce(collection, 0, fn v, acc -> acc + 1 end)}
end
def count(collection) do
{:error, __MODULE__}
end
def member?(collection, value) when is_binary(collection) do
{:ok, Enum.any?(collection, fn v -> value == v end)}
end
def member?(collection, value) do
{:error, __MODULE__}
end
def reduce(b, {:halt, acc}, _fun) when is_binary(b) do
{:halted, acc}
end
def reduce(b, {:suspend, acc}, fun) when is_binary(b) do
{:suspended, acc, &reduce(b, &1, fun)}
end
def reduce(<<>>, {:cont, acc}, _fun) do
{:done, acc}
end
def reduce(<<h :: bytes-size(1), t :: binary>>, {:cont, acc}, fun) do
reduce(t, fun.(h, acc), fun)
end
end
end
# USAGE EXAMPLES
# NOTE: IN ORDER TO GET THIS TO WORK I HAD TO USE MIX_ENV=prod (for protocol consolidation)
# the easier way to do this is to add the following line to your project definition in mix.exs:
# consolidate_protocols: true,
$ MIX_ENV=prod iex -S mix
iex>> import Benum
iex>> Enum.count "foobar"
6
iex>> Enum.count <<1,2,3>>
3
iex>> Enum.count ""
0
iex>> Enum.member? "foobar", "b"
true
iex>> Enum.member? "foobar", <<98>>
true
iex>> Enum.member? "foobar", "x"
false
iex>> Enum.map("foobar", &String.upcase/1) |> Enum.into <<>>
"FOOBAR"
iex>> Enum.join "foobar", "."
"f.o.o.b.a.r"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment