Created
March 18, 2018 10:49
-
-
Save savonarola/e99337edc00789919290dc21b0bc3f61 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule FindIndex do | |
def find_index(list, pred, index \\ 0) | |
def find_index([], _pred, _index), do: :notfound | |
def find_index([el | rest], pred, index) do | |
case pred.(el) do | |
{:ok, value} -> {:ok, value, index} | |
:notfound -> find_index(rest, pred, index + 1) | |
end | |
end | |
def contains?(el, pattern) do | |
if String.contains?(el, pattern) do | |
{:ok, el} | |
else | |
:notfound | |
end | |
end | |
def find_matrix_index(matrix, pattern) do | |
found_in_matrix? = find_index(matrix, fn(row) -> | |
found_in_row? = find_index(row, &contains?(&1, pattern)) | |
case found_in_row? do | |
{:ok, _el, col_index} -> {:ok, col_index} | |
:notfound -> :notfound | |
end | |
end) | |
case found_in_matrix? do | |
{:ok, col_index, row_index} -> {row_index, col_index} | |
:notfound -> nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment