我怎么能在灵药中加倍列表?

时间:2017-02-13 07:51:00

标签: elixir

我有一个清单

[1, 4, 3]

我想将它增加,例如:

[1, 4, 3] * 3 # => [1, 4, 3, 1, 4, 3, 1, 4, 3]

我该怎么做?

4 个答案:

答案 0 :(得分:7)

我相信,Elixir惯用解决方案是使用List.duplicate/2

list |> List.duplicate(3) |> List.flatten

请注意,如果list预计会有嵌套列表,并且它们不会被展平,则应使用:

list |> List.duplicate(3) |> :lists.concat

- 积分转到@Dogbert

答案 1 :(得分:5)

我将Enum.map:lists.concat一起使用(Enum.concat:lists.concat慢得多):

:lists.concat(Enum.map(1..100, fn(_) -> @list end))

以下是本主题中的建议以及其他一些尝试的基准:

defmodule BasicBench do
  use Benchfella

  @list Enum.to_list(1..100)

  bench "1 by @asiniy" do
    Enum.reduce(1..100, [], fn(_, acc) -> acc ++ @list end)
  end

  bench "2 by @radubogdan" do
    Enum.take(Stream.cycle(@list), 10000)
  end

  bench "3 by @Dogbert" do
    Enum.flat_map(1..100, fn(_) -> @list end)
  end

  bench "4 by @Dogbert" do
    Enum.concat(Enum.map(1..100, fn(_) -> @list end))
  end

  bench "5 by @Dogbert" do
    :lists.concat(Enum.map(1..100, fn(_) -> @list end))
  end

  bench "6 by @mudasobwa" do
    @list |> List.duplicate(100) |> List.flatten
  end

  bench "7 by @mudasobwa + @Dogbert" do
    :lists.concat(List.duplicate(@list, 100))
  end
end

输出:

benchmark name              iterations   average time
7 by @mudasobwa + @Dogbert       50000   35.72 µs/op
5 by @Dogbert                    50000   38.92 µs/op
6 by @mudasobwa                  10000   124.30 µs/op
3 by @Dogbert                    10000   174.63 µs/op
4 by @Dogbert                    10000   242.24 µs/op
2 by @radubogdan                  2000   924.04 µs/op
1 by @asiniy                      1000   2143.24 µs/op

答案 2 :(得分:3)

我会使用Stream.cycle/1

iex> stream = Stream.cycle([1, 4, 3])
iex> Enum.take(stream, 9)
[1, 4, 3, 1, 4, 3, 1, 4, 3]

答案 3 :(得分:0)

最让人想到的是:

def multiply_list(list, factor) do
  Enum.reduce(1..factor, [], fn(_, acc) -> acc ++ list end)
end