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

2019-07-27 11:24发布

问题:

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:

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.