Search code examples
listfiltererlangzip

Erlang: Filter elements from multiple lists based on user input


I have 3 Lists in erlang as

EmpIDList = [10020, 10010, 10040, 10030],
EmpLocation = [Sweden, Germany, USA, Italy],
EmpSalary = [100k, 125k, 165k, 200k]

If user provides the input as [10040, 10020] then the expected output is 3 Lists:

[10040, 10020], [USA, Sweden], [165k, 100k].

How to achieve this? Any input will be helpful.

Note:

  1. all 3 lists will always have same number of elements.
  2. The first element from EmpLocation corresponds to first element in EmpIDList and so on.
  3. The first element from EmpSalary corresponds to first element in EmpIDList and so on.

Solution

  • First combine the data from the three lists using lists:zip3, so that data for each employee is kept together:

    > EmpList = lists:zip3(EmpIDList, EmpLocation, EmpSalary).
    [{10020,sweden,100},
     {10010,germany,125},
     {10040,usa,165},
     {10030,italy,200}]
    

    Then use lists:keyfind to get the employees you are interested in - note the list of employee ids near the end:

    > FilteredTuples = [lists:keyfind(Id, 1, EmpList) || Id <- [10040, 10020]].
    [{10040,usa,165},{10020,sweden,100}]
    

    And finally "unzip" the tuples to get the result format you need:

    > lists:unzip3(FilteredTuples).
    {[10040,10020],[usa,sweden],[165,100]}