【问题标题】:How to rewrite Erlang combinations algorithm in Elixir?如何在 Elixir 中重写 Erlang 组合算法?
【发布时间】: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


    【解决方案1】:

    您需要像 Erlang 代码一样将 for 表达式包裹在括号中。

    def combination(n, [x|xs]) do
      (for y <- combination(n - 1, xs), do: [x|y]) ++ combination(n, xs)
    end
    

    演示:

    iex(1)> defmodule Foo do
    ...(1)>   def combination(0, _), do: [[]]
    ...(1)>   def combination(_, []), do: []
    ...(1)>   def combination(n, [x|xs]) do
    ...(1)>     (for y <- combination(n - 1, xs), do: [x|y]) ++ combination(n, xs)
    ...(1)>   end
    ...(1)> end
    {:module, Foo,
     <<70, 79, 82, 49, 0, 0, 6, 100, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 137, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 2, 104, 2, ...>>,
     {:combination, 2}}
    iex(2)> Foo.combination 2, [1, 2, 3]
    [[1, 2], [1, 3], [2, 3]]
    

    【讨论】:

    • 太棒了!谢谢你。 :)
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2017-11-03
    • 2019-07-05
    • 2016-05-18
    • 2016-12-04
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多