如何在Elixir中重写Erlang组合算法? [英] How to rewrite Erlang combinations algorithm in Elixir?

查看:84
本文介绍了如何在Elixir中重写Erlang组合算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几个星期里,我一直在修补Elixir。我刚刚遇到了这个简洁的 Erlang 中的组合算法,我尝试在Elixir中重写,但被卡住了。



Erlang版本:

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

Elixir版本我想出了这一点,但这是不正确的:

  def组合(0,_),do:[[]] 
def组合(_,[]),do:[] $ b $对于y <组合(n-1,xs),b def组合(n,[x | xs])do
,do:[x | y] ++组合(n,xs)
结束

示例用法,结果不正确:

  IEX>组合(2,[1,2,3])
[[1,2,[3],[2,3]]]

任何关于我做错什么的指针?



谢谢!

Sean

解决方案

您需要将表达式包含在括号中,如Erlang代码。

  def组合(n,[x | xs])do 
(对于y <组合(n - 1,xs),do:[x | y])+ +组合(n,xs)
end

演示:

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


I've been tinkering with Elixir for the last few weeks. I just came across this succinct combinations algorithm in Erlang, which I tried rewriting in Elixir but got stuck.

Erlang version:

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

Elixir version I came up with this, but it's not correct:

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

Example usage, with incorrect results:

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

Any pointers on what I'm doing wrong?

Thanks!
Sean

解决方案

You need to wrap the for expression in parentheses like the Erlang code.

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

这篇关于如何在Elixir中重写Erlang组合算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆