gpt4 book ai didi

arrays - 在 Elixir 中从列表中查找索引

转载 作者:行者123 更新时间:2023-12-04 12:48:06 27 4
gpt4 key购买 nike

Enum.find_index/2 ,我们可以找到一个元素的索引。
但是,如果同一个元素出现多次,怎么办?

我想有这种行为:

iex> find_indexes(["a", "b", "c", "b", "b"], fn(x) -> x == "a" end)
[0]

iex> find_indexes(["a", "b", "c", "b", "b"], fn(x) -> x == "c" end)
[2]

iex> find_indexes(["a", "b", "c", "b", "b"], fn(x) -> x == "b" end)
[1, 3, 4]

感谢您的任何想法。

最佳答案

我在库中找不到确切的函数,所以尝试实现它。希望它可以帮助一些。

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)

执行如下,
% elixir find.ex
Sample1
[0]
[2]
[1, 3, 4]
Sample2
[0]
[2]
[1, 3, 4]

关于arrays - 在 Elixir 中从列表中查找索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18551814/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com