daily pastebin goal
20%
SHARE
TWEET

[C] List Traversal with map function

cwchen Apr 18th, 2018 154 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. bool test_list_map()
  2. {
  3.     // Nested function, available in GCC.
  4.     int square(int n)
  5.     {
  6.         return n * n;
  7.     }
  8.  
  9.     bool failed = false;
  10.    
  11.     // List p: 1 -> 2 -> 3 -> NULL
  12.     List *lp = list_init(3, 1, 2, 3);
  13.     if (lp == NULL) {
  14.         perror("Failed to allocate List lp");
  15.         return false;
  16.     }
  17.  
  18.     // List q: 1 -> 4 -> 9 -> NULL
  19.     // Traverse in functional style.
  20.     List *lq = list_map(lp, square);
  21.     if (lq == NULL) {
  22.         perror("Failed to allocate List lq");
  23.         failed = true;
  24.         goto LIST_P_FREE;
  25.     }
  26.  
  27.     int arr[] = {1, 4, 9};
  28.     size_t i = 0;
  29.     for (Node *it = list_start(lq); !list_end(it); it = list_next(it)) {
  30.         if (node_value(it) != arr[i]) {
  31.             failed = true;
  32.             goto LIST_Q_FREE;
  33.         }
  34.        
  35.         i++;
  36.     }
  37.  
  38. LIST_Q_FREE:
  39.     list_free(lq);
  40. LIST_P_FREE:
  41.     list_free(lp);
  42.    
  43.     if (failed) {
  44.         return false;
  45.     }
  46.    
  47.     return true;
  48. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top