Skip to content

Instantly share code, notes, and snippets.

@apboobalan
Last active October 14, 2020 06:30
Show Gist options
  • Select an option

  • Save apboobalan/e840421c54af33bcdf952289572ea6b8 to your computer and use it in GitHub Desktop.

Select an option

Save apboobalan/e840421c54af33bcdf952289572ea6b8 to your computer and use it in GitHub Desktop.
Curious case of 'in'. Add in capability to strings in Elixir.
defimpl Enumerable, for: BitString do
def count(string), do: {:ok, string |> String.length()}
def member?(string, substring), do: {:ok, string |> String.contains?(substring)}
def slice(string),
do:
{:ok, string |> String.length(),
fn start_position, end_position ->
string
|> String.slice(start_position, end_position)
|> to_list()
end}
def reduce(_list, {:halt, acc}, _fun), do: {:halted, acc}
def reduce(list, {:suspend, acc}, fun) when list |> is_binary(), do: list |> to_list |> reduce({:suspend, acc}, fun)
def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}
def reduce(list, {:cont, acc}, fun) when list |> is_binary(), do: list |> to_list |> reduce({:cont, acc}, fun)
def reduce([], {:cont, acc}, _fun), do: {:done, acc}
def reduce([head | tail], {:cont, acc}, fun), do: tail |> reduce(fun.(head, acc), fun)
defp to_list(string), do: string |> String.split("") |> Enum.reject(& &1 == "")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment