简体   繁体   English

Erlang组合学

[英]Combinatorics in Erlang

I want to find combinatorics of integer in Erlang, equivalent of this Haskell code: 我想在Erlang中找到整数的组合,它等效于此Haskell代码:

composition 0 = [[]]
composition n = [x:rest | x <- [1..n], rest <- composition (n-x)]

so far I tried this which It doesn't work: 到目前为止,我已经尝试了这不起作用:

-module(combinatorics).
-export([comb/1]).
comb([]) -> []; 
comb(N) ->
        [[X|R] || X <- lists:seq(1,N),R=comb(N-X)].

The code return This error: 代码返回此错误:

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)

You have multiple errors in the translation: 您在翻译中存在多个错误:

  1. The first clause should be comb(0) -> [[]]; 第一个子句应为comb(0) -> [[]];

  2. You've done R = comb(...) instead of R <- comb(...) in the list comprehension. 您已经完成了R = comb(...)而不是列表理解中的R <- comb(...)

With these changes, the code works: 通过这些更改,代码可以工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM