2015-06-02 7 views
11

Ich habe in den letzten Wochen mit Elixir gebastelt. Ich bin gerade auf diese knappe combinations algorithm in Erlang gestoßen, die ich in Elixir umgeschrieben habe, aber stecken geblieben bin.Wie Erlang Kombinationen Algorithmus in Elixir umschreiben?

Erlang Version:

comb(0,_) -> 
    [[]]; 
comb(_,[]) -> 
    []; 
comb(N,[H|T]) -> 
    [[H|L] || L <- comb(N-1,T)]++comb(N,T). 

Elixir Version kam ich mit diesem, aber es ist nicht korrekt:

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 

Beispiel für die Verwendung mit falschen Ergebnissen:

iex> combination(2, [1,2,3]) 
[[1, 2, [3], [2, 3]]] 

Alle Hinweise was mache ich falsch?

Danke!
Sean

Antwort

13

Sie müssen den für Ausdruck in Klammern wie den Erlang-Code umbrechen.

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

Demo:

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]] 
+0

Excellent! Vielen Dank. :) – seanomlor

Verwandte Themen