我想在Erlang中找到整数的组合,相当于这个Haskell代码:
composition 0 = [[]]
composition n = [x:rest | x <- [1..n], rest <- composition (n-x)]到目前为止,我尝试过这种方法,但它不起作用:
-module(combinatorics).
-export([comb/1]).
comb([]) -> [];
comb(N) ->
[[X|R] || X <- lists:seq(1,N),R=comb(N-X)].代码返回此错误:
43> combinatorics:comb(2).
** exception error: no case clause matching []
in function combinatorics:'-comb/1-lc$^0/1-0-'/2 (combinatorics.erl, line 5)
in call from combinatorics:'-comb/1-lc$^0/1-0-'/2 (combinatorics.erl, line 5)发布于 2017-05-24 10:54:09
翻译中有多个错误:
comb(0) -> [[]];R = comb(...)而不是R <- comb(...)。通过这些更改,代码工作如下:
-module(combinatorics).
-export([comb/1]).
comb(0) -> [[]];
comb(N) ->
[[X|R] || X <- lists:seq(1,N), R <- comb(N-X)].1> c(combinatorics).
{ok,combinatorics}
2> combinatorics:comb(1).
[[1]]
3> combinatorics:comb(2).
[[1,1],[2]]
4> combinatorics:comb(3).
[[1,1,1],[1,2],[2,1],[3]]
5> combinatorics:comb(4).
[[1,1,1,1],[1,1,2],[1,2,1],[1,3],[2,1,1],[2,2],[3,1],[4]]https://stackoverflow.com/questions/44155749
复制相似问题