elixir - 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 获得了上述代码。
解决方案
与 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)
推荐阅读
- ios - 在编辑不同的正则表达式时检查 UITextField
- r - group_by 变量和 dplyr 中的总和
- python - 如果所有行都是 nan,则将 pandas 数据帧拆分为多个数据帧
- reactjs - 使用 Redux 将类组件转换为功能组件
- react-native - 我如何在本机反应中访问组件中的属性
- go - 如何在 gRPC 调用中直接传递原始二进制文件?
- ios - Xcode 11:如何让我的内容以横向和纵向显示这样的?
- kubernetes - 用堆叠的控制平面替换 Kubernetes 1.15 集群中的死主
- unity3d - TextMeshPro 文本颜色在移动时重置
- html - 我的响应式菜单在悬停时无法正确显示,并且菜单内容是透明的