Created
March 1, 2017 20:23
-
-
Save henryhamon/cd5c7c7679f41b4bbc7bb2cb23bfda65 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Sample1 do | |
# combining Enum functions | |
def find_indexes(collection, function) do | |
Enum.filter_map(Enum.with_index(collection), fn({x, _y}) -> function.(x) end, elem(&1, 1)) | |
end | |
end | |
defmodule Sample2 do | |
# implementing as similar way as Enum.find_index | |
def find_indexes(collection, function) do | |
do_find_indexes(collection, function, 0, []) | |
end | |
def do_find_indexes([], _function, _counter, acc) do | |
Enum.reverse(acc) | |
end | |
def do_find_indexes([h|t], function, counter, acc) do | |
if function.(h) do | |
do_find_indexes(t, function, counter + 1, [counter|acc]) | |
else | |
do_find_indexes(t, function, counter + 1, acc) | |
end | |
end | |
end | |
IO.puts "Sample1" | |
IO.inspect Sample1.find_indexes(["a", "b", "c", "b", "b"], fn(x) -> x == "a" end) | |
IO.inspect Sample1.find_indexes(["a", "b", "c", "b", "b"], fn(x) -> x == "c" end) | |
IO.inspect Sample1.find_indexes(["a", "b", "c", "b", "b"], fn(x) -> x == "b" end) | |
IO.puts "Sample2" | |
IO.inspect Sample2.find_indexes(["a", "b", "c", "b", "b"], fn(x) -> x == "a" end) | |
IO.inspect Sample2.find_indexes(["a", "b", "c", "b", "b"], fn(x) -> x == "c" end) | |
IO.inspect Sample2.find_indexes(["a", "b", "c", "b", "b"], fn(x) -> x == "b" end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment