将一个Erlang列表X拆分成所有X的子列表的列表 [英] Split An Erlang List, X, into a List of All X's Sublists

查看:219
本文介绍了将一个Erlang列表X拆分成所有X的子列表的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列表:sublist / 2 列表:sublist / 3 使得简单的提取单个子列表从列表,但是是否有一个BiF或模块返回所有列表的子列表的列表?

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?

ie

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]]

可以建立自己的,但想知道问题是否在任何地方解决? p>

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

推荐答案

我假设你的测试用例是遗忘的[1,3,4],但它可能看起来像这样:

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.

这篇关于将一个Erlang列表X拆分成所有X的子列表的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆