首页 > 解决方案 > Elixir 内置组合方法?

问题描述

defmodule Itertools
    def combinations(_, 0), do: [[]] 
    def combinations([], _), do: [] 
    def combinations([h|t], m) do 
        (for l <- combinations(t, m-1), do: [h|l]) ++ combinations(t, m) 
    end 
end 

我正在处理一个数组上的嵌套循环,该数组可以由 Python 的 itertools.combinations 之类的东西处理,但在标准库中看不到。Elixir 是否在某个地方内置了它,还是有更好的方法来模拟 Elixir 中列表的三角循环?

顺便说一句,我从 rosettacode.org 获得了上述代码。

标签: elixircombinations

解决方案


与 Erlang 类似,Elixir 没有内置函数来进行组合。正如 Rosettacode 所说“这个 Elixir 代码刚刚从 Erlang 转换而来”:

defmodule RC do
  def comb(0, _), do: [[]]
  def comb(_, []), do: []
  def comb(m, [h|t]) do
    (for l <- comb(m-1, t), do: [h|l]) ++ comb(m, t)
  end
end

{m, n} = {3, 5}
list = for i <- 1..n, do: i
Enum.each(RC.comb(m, list), fn x -> IO.inspect x end)

https://rosettacode.org/wiki/Combinations#Elixir


推荐阅读