Erlang List对笛卡尔积的理解

时间:2017-12-28 14:11:45

标签: erlang list-comprehension cartesian-product

我正在学习Erlang并且遇到过/试图理解列表理解。我发现你可以很容易地使用笛卡尔产品。

基本上我虽然是一副纸牌,如果你将独特的数值乘以套装的数量,你将得到每一种可能的组合 - 创造一整套纸牌。但是,如果我希望将2个笑话添加到套牌中,那么该怎么办 - 但是笑话者不属于诉讼。我们如何解决这个问题?

以下代码是我目前所拥有的代码,并且将输出可能的组合,而不是笑话。

SELECT (EXTRACT(epoch FROM (
case when 
    (select date from history where statut='X' and id=6 order by date desc limit 1) 
     is null then now() 
  else 
    (select date from history where statut='X' and id=6 order by date desc limit 1) end)
- case when 
    (select date from history where statut in ('Y', 'U') and id=6 order by date desc limit 1) 
     is null then now() 
else 
 (select date from history where statut in ('Y', 'U')  and id=6 order by date desc limit 1) 
 end 
)/3600)

是否有更好的实现方式/如何实现这一目标? 我希望这个笑话的输出会像{joker,nosuit} 谢谢, Snelly。

1 个答案:

答案 0 :(得分:1)

如果你真的想直接从列表理解中获取它,你可以使用过滤器:

CardValues = [joker,joker,ace, king, queen, jack, 10, 9, 8, 7, 6, 5, 4, 3, 2],
CardSuits =  [spades,hearts,clubs,diamonds,nosuit],
CartesianList = [{X, Y} || X <- CardValues, Y <- CardSuits, ((X == joker)andalso(Y==nosuit))orelse((X =/= joker)andalso(Y=/=nosuit)) ],
io:format("\nCartesianList:~p\n",[CartesianList]).

但它真的很奇怪,人为和低效,我会手动添加它们:

CardValues = [ace, king, queen, jack, 10, 9, 8, 7, 6, 5, 4, 3, 2],
CardSuits =  [spades,hearts,clubs,diamonds],
CartesianList = [{joker,nosuit},{joker,nosuit}|[{X, Y} || X <- CardValues, Y <- CardSuits ]]],
io:format("\nCartesianList:~p\n",[CartesianList]).