问题
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.
来源:https://stackoverflow.com/questions/4455632/split-an-erlang-list-x-into-a-list-of-all-xs-sublists