首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >二郎中的组合学

二郎中的组合学
EN

Stack Overflow用户
提问于 2017-05-24 10:28:29
回答 1查看 114关注 0票数 0

我想在Erlang中找到整数的组合,相当于这个Haskell代码:

代码语言:javascript
复制
composition 0 = [[]]
composition n = [x:rest | x <- [1..n], rest <- composition (n-x)]

到目前为止,我尝试过这种方法,但它不起作用:

代码语言:javascript
复制
-module(combinatorics).
-export([comb/1]).
comb([]) -> []; 
comb(N) ->
        [[X|R] || X <- lists:seq(1,N),R=comb(N-X)].

代码返回此错误:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-24 10:54:09

翻译中有多个错误:

  1. 第一句应该是comb(0) -> [[]];
  2. 在列表理解中,您已经完成了R = comb(...)而不是R <- comb(...)

通过这些更改,代码工作如下:

代码语言:javascript
复制
-module(combinatorics).
-export([comb/1]).
comb(0) -> [[]];
comb(N) ->
    [[X|R] || X <- lists:seq(1,N), R <- comb(N-X)].
代码语言:javascript
复制
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]]
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44155749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档