假设我有两个列表:AmountOfProducts,它包含一个元组列表,如
[{apple, 10}, {chocolate, 13}, {lettuce, 9}, {mango, 20}]
第二个列表是OrderProducts,它包含如下元组:
[{apple, 3}, {chocolate, 1}, {mango 4}]
第一个元素是产品名称的原子,第二个元素是数量,对于AmountOfProducts,数量是可用的数量,对于OrderProducts,数量是要求的数量。是否有方法检查OrderProducts的所有原子是否都存在于AmountOfProducts中并返回true?如果,假设OrderProducts有一个额外的元组,并且它的原子不存在于AmountOfProducts中,它将返回false。
AmountOfProducts = [{apple, 10}, {chocolate, 13}, {lettuce, 9}, {mango, 20}]
OrderProducts = [{apple, 3}, {chocolate, 1}, {mango 4}]
check_products(AmountOfProducts, OrderProducts) ->
if
all atoms inside OrderProducts exists in AmountOfProducts -> true;
one or many of the atoms inside OrderProducts doesnt exist in AmountOfProducts -> false
end.
在给定的两个列表的情况下,它应该返回为真。有什么方法可以做到这一点吗?我希望这是有意义的,谢谢!
1条答案
按热度按时间lokaqttq1#
I'll show you several ways to solve this problem.
First Version: List Comprehensions
Here we basically collect all the keys in
OrderProducts
that don't have a corresponding tuple inAmountOfProducts
and, if that's an empty list… we returntrue
Second Version: High-Order Functions
Here we basically write what you wrote in your question, but in Erlang code: Return
true
if the keys of all the elements inOrderProduct
are also keys inAmountOfProducts
.Third Version: Just compare the Keys
Now, if you know that there will be no duplication of keys in any of the lists, you can also write your code like this…
Basically saying that if we remove all the keys from
AmountOfProducts
from the list of keys ofOrderProducts
... we end up with no keys (they were all removed because they belonged toAmountOfProducts
). You have to implement an auxiliary functionkeys/1
, but that one is hopefully much easier to implement (or you can just useproplists:get_keys/1
.