Arrays 从Elixir中的列表中查找索引

Arrays 从Elixir中的列表中查找索引,arrays,functional-programming,elixir,Arrays,Functional Programming,Elixir,使用,我们可以找到元素的索引。 但是,如果同一元素多次出现,我们该怎么办 我希望有这样的行为: 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

使用,我们可以找到元素的索引。 但是,如果同一元素多次出现,我们该怎么办

我希望有这样的行为:

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]

或者,您可以压缩范围为
0..length(list)
的列表,并使用新项目筛选列表:

line = IO.read(:stdio, :all) 
|> String.split
|> Enum.zip(0..100)
|> Enum.filter(fn({_, x}) -> rem(x, 2) != 0 end)
|> Enum.map(fn({x, _}) -> "#{x}\n" end)
从stdin中筛选给定列表上的奇数元素


请注意,范围(
0..100
)中的100必须是列表的长度。我想我有一张100个项目的清单。

谢谢你的帮助@parroty!我们还可以使用:
Enum.with_index([“a”,“b”,“c”,“b”,“b”]))\124;>Enum.filter_映射(fn{x,{u}->x==“b”end,fn{uo,i}->i end)
Yeah。这更像是长生不老药。