0

The following is a naive attempt to increase the concurrency of the Filter function:

fun {Filter L F}
      case L of
          X|Xs then if thread {F X} end
                    then X|{Filter Xs F}
                    else {Filter Xs F} end
          else nil
      end
end

What is an alternative Filter operation with better concurrency (code)? (Hint : You may make make use of message-passing concurrency.)

1 Answers1

0

The current code evaluates an item of the list, then the next one, sequentially until the end of the list. One way to add concurrency to the code is to divide the logic into two parts: Evaluation and appending to the result list.


Evaluation: Loop through the list and evaluate each item in a separate thread, and store the results in a boolean list.

Append: Loop through the boolean list (concurrently while it is being created) and if the values are true, add to the result list. Skip all the false values.


Example solution:

fun {FilterConc L F}
   ResultBool
   fun {Evaluate L F}
      case L of X|Xs then
      thread {F X} end|{Evaluate Xs F}
      else nil end
   end

   fun {AppendLoop L1 ResultBool1}
      case ResultBool1 of R|Rs then
      case L1 of X|Xs then
         case R of true then
            X|{AppendLoop Xs Rs}
         else {AppendLoop Xs Rs} end
      else nil end
      else nil end
   end
in
   ResultBool = {Evaluate L F}
   %{Browse ResultBool}       ---> shows [true false false false true true true]
   {AppendLoop L ResultBool}
end

{Show {FilterConc [1 2 4 6 121 52381 1235] Int.isOdd}}
% ---> shows [1 121 52381 1235]
Timmy Chan
  • 933
  • 7
  • 15