Erlang如何检查一个元组列表中的所有元素是否都存在于另一个元组列表中

ijxebb2r  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(282)

假设我有两个列表: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.

在给定的两个列表的情况下,它应该返回为真。有什么方法可以做到这一点吗?我希望这是有意义的,谢谢!

lokaqttq

lokaqttq1#

I'll show you several ways to solve this problem.

First Version: List Comprehensions

check_products(AmountOfProducts, OrderProducts) ->
  [] ==
    [Key || {Key, _} <- OrderProducts
          , not lists:keymember(Key, 1, AmountOfProducts)].

Here we basically collect all the keys in OrderProducts that don't have a corresponding tuple in AmountOfProducts and, if that's an empty list… we return true

Second Version: High-Order Functions

check_products(AmountOfProducts, OrderProducts) ->
  lists:all(
    fun({Key, _}) ->
      lists:keymember(Key, 1, AmountOfProducts)
    end, OrderProducts).

Here we basically write what you wrote in your question, but in Erlang code: Return true if the keys of all the elements in OrderProduct are also keys in AmountOfProducts .

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…

check_products(AmountOfProducts, OrderProducts) ->
  [] == keys(OrderProducts) -- keys(AmountOfProducts).

Basically saying that if we remove all the keys from AmountOfProducts from the list of keys of OrderProducts ... we end up with no keys (they were all removed because they belonged to AmountOfProducts ). You have to implement an auxiliary function keys/1 , but that one is hopefully much easier to implement (or you can just use proplists:get_keys/1.

相关问题