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

大城市里の小女人 提交于 2020-01-05 05:37:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!