【发布时间】:2015-08-15 15:11:03
【问题描述】:
过去几周我一直在修补 Elixir。我刚刚遇到了这个简洁的combinations algorithm in Erlang,我尝试在 Elixir 中重写,但被卡住了。
Erlang 版本:
comb(0,_) ->
[[]];
comb(_,[]) ->
[];
comb(N,[H|T]) ->
[[H|L] || L <- comb(N-1,T)]++comb(N,T).
Elixir 版本我想出了这个,但它不正确:
def combination(0, _), do: [[]]
def combination(_, []), do: []
def combination(n, [x|xs]) do
for y <- combination(n - 1, xs), do: [x|y] ++ combination(n, xs)
end
示例用法,结果不正确:
iex> combination(2, [1,2,3])
[[1, 2, [3], [2, 3]]]
任何关于我做错了什么的指针?
谢谢!
肖恩
【问题讨论】:
标签: functional-programming erlang elixir