Split An Erlang List, X, into a List of All X'

2019-07-27 11:52发布

lists:sublist/2 and lists:sublist/3 make it simple to extract a single sublist from a list, but is there a BiF or module that returns a list of all of a list's sublists?

i.e.

lists:awesome_sublist_function([1,2,3,4]) ->
  [[1], [2], [3], [4], [1,2], [1,3], [1,4], 
  [2,3], [2,4], [3,4], [1,2,3], [1,2,4], [1,3,4], [2,3,4], [1,2,3,4]]

Can build my own, but wondered if the problem has been solved before anywhere?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-27 12:10

I assume your test case is forgetting [1,3,4], but it could look something like this:

-module(settheory).
-export([combinations/1]).

combinations([]) ->
    [];
combinations([H | T]) ->
    CT = combinations(T),
    [[H]] ++ [[H | L] || L <- CT] ++ CT.

-include_lib("eunit/include/eunit.hrl").
combinations_test() ->
    ?assertEqual(
       combinations([1,2,3,4]),
       lists:sort([[1], [2], [3], [4], [1,2], [1,3], [1,4],
                   [2,3], [2,4], [3,4], [1,2,3], [1,2,4], [1,3,4],
                   [2,3,4], [1,2,3,4]])),
    ok.
查看更多
登录 后发表回答