How to check the response of each item in a list comprehension

In the following code, I want to check the result of each call to start_itemis okor not. Cannot be added ok=to start_item.

start_item_group(Community_code,Category_code,Group_code)->
    [
     start_item(Community_code,Category_code,Item_seq_no)
     ||
     {_Community_code,_Category_code,Item_seq_no} 
     <-
     dis_scan:get_group_item(Community_code,Category_code,Group_code),    
    ok.
+3
source share
4 answers

I already did something similar before, but in a different way. I also needed to check the result of the expression. The advantage of my trick is that you do not need to test it yourself; pattern matching does this for you. The key to the trick is to use lists: foldl. The following is an example.

check_group(Community_code,Category_code,Group_code) ->
    Group = dis_scan:get_group_item(Community_code,Category_code,Group_code),
    StartItems = [ start_item(Community_code,Category_code,Item_seq_no) 
               || {_, _, Item_seq_no } <- Group ],
    ok = lists:foldl(fun check_start_item/2, ok, StartItems),
    exit(normal).

check_start_item(StartItem, ok) -> 
    ## Return ok if item is ok, {error, Reason} otherwise.
    ok.

If, on the other hand, you need to group the items by the result returned from the scan, then use the lists: section.

check_group(Community_code,Category_code,Group_code) ->
    Group = dis_scan:get_group_item(Community_code,Category_code,Group_code),
    StartItems = [ start_item(Community_code,Category_code,Item_seq_no) 
               || {_, _, Item_seq_no } <- Group ],
    {GoodItems, BadItems} = lists:partition(fun check_start_item/1, StartItems),
    case BadItems of 
        [] -> exit(normal);
         _ -> error({bad_start_items, BadItems})
    end.

check_start_item(StartItem) -> 
    ## Return true if item is ok, false otherwise.
    true.
+1
source

, , start_item ok, ! :

start_item_group(Community_code,Category_code,Group_code)->
  Failed = [
    Item ||
    {_Comm_code, _Cat_code, Item} <- dis_scan:get_group_item(Community_code,Category_code,Group_code),
    ok =/= start_item(Community_code, Category_code, Item)
  ],
  do_stuff_with(Failed).
+2

: foreach. foreach , , .

+1

-, start_item , , "ok" ( "ok" ):

start_item_check(ok) ->
  %% return/do whatever needs to be done if response is ok;
start_item_check(not_ok) ->
  %% return/do whatever needs to be done if response is not ok;
start_item_check(StartItemResponse) ->
  %% do whatever needs to be done if not 'ok' nor 'not_ok';
  %% it up to your business logic.

start_item_group(Community_code,Category_code,Group_code) ->
  [
    start_item_check(start_item(Community_code,Category_code,Item_seq_no))
    ||
    {_Community_code,_Category_code,Item_seq_no}
    <-
    dis_scan:get_group_item(Community_code,Category_code,Group_code)
  ].

"start_item", : , . , , ; : foreach W55tKQbuRu28Q4xv prev. .

+1

All Articles