二郎神;列表理解没有重复 [英] Erlang; list comprehension without duplicates

查看:155
本文介绍了二郎神;列表理解没有重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些可怕的事情,但我不知道如何使它更好。



我正在形成名为SomeList的列表的所有成对总和,但我不想看到重复(我想我想要所有可能的成对总和):

  sets:to_list set:from_list([A + B || A < -  SomeList,B<  -  SomeList]))



SomeList不包含重复项。



这是有效的,但是效率低下,因为设置转换前的原始列表是GIGANTIC。



有更好的方法吗?

解决方案

你可以使用列表:usort / 1



列表:usort([X + Y || X <-L,Y <-L])。如果有重复的机会很高,那么你就可以可以使用2个循环生成和,并将这个总和存储在一个 集合(或使用映射中,我没有检查两者的性能)。

  7> Inloop = fun Inloop(_,[],_) - >好; Inloop(Store,[H | T],X) - > ets:insert(Store,{X + H}),Inloop(Store,T,X)结束。 
#Fun< erl_eval.42.54118792>
8> Outloop = fun Outloop(Store,[],_) - >好; Outloop(Store,[H | T],List) - > Inloop(Store,List,H),Outloop(Store,T,List)结束。
#Fun< erl_eval.42.54118792>
9> Makesum = fun(L) - > S = ets:new(temp,[set]),Outloop(S,L,L),R = ets:foldl(fun({X},Acc))> [X | Acc] end,[] ),ets:delete(S),R end。
#Fun< erl_eval.6.54118792>
10> Makesum(名单:SEQ(1,10))。
[15,13,​​8,11,20,14,16,12,7,3,10,9,19,18,4,17,6,2,5]
11>清单:排序(Makesum(名单:SEQ(1,10)))。
[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
12>


I am doing somthing horrible but I don't know how to make it better.

I am forming all pairwise sums of the elements of a List called SomeList, but I don't want to see duplicates ( I guess I want "all possible pairwise sums" ):

sets:to_list(sets:from_list([A+B || A <- SomeList, B <- SomeList]))

SomeList does NOT contain duplicates.

This works, but is horribly inefficient, because the original list before the set conversion is GIGANTIC.

Is there a better way to do this?

解决方案

You could simply use lists:usort/1

lists:usort([X+Y || X <- L, Y <- L]).

if the chance to have duplicates is very high, then you can generate the sum using 2 loops and store the sum in an ets set (or using map, I didn't check the performance of both).

7> Inloop = fun Inloop(_,[],_) -> ok; Inloop(Store,[H|T],X) -> ets:insert(Store,{X+H}), Inloop(Store,T,X) end.
#Fun<erl_eval.42.54118792>
8> Outloop = fun Outloop(Store,[],_) -> ok; Outloop(Store,[H|T],List) -> Inloop(Store,List,H), Outloop(Store,T,List) end.
#Fun<erl_eval.42.54118792>
9> Makesum = fun(L) -> S = ets:new(temp,[set]), Outloop(S,L,L), R =ets:foldl(fun({X},Acc) -> [X|Acc] end,[],S), ets:delete(S), R end.
#Fun<erl_eval.6.54118792>
10> Makesum(lists:seq(1,10)).
[15,13,8,11,20,14,16,12,7,3,10,9,19,18,4,17,6,2,5]
11> lists:sort(Makesum(lists:seq(1,10))).
[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
12> 

这篇关于二郎神;列表理解没有重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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