index---files

Programing: map, reduce and filter

One aspect of functional programing is the ability to pass functions as parameters to another functions. In the end we would get code in this form f(x, g) while f and g are functions and x is data. A language that supports that construct is told to have functions as first class citizens. An example of a function that takes another function as a parameter is map:

    function map(x, mapper) {
      let _internal_map = [];
      for (let element of x) {
        _internal_map.push(mapper(element));
      }
        return _internal_map;
    }
    

So as it is clear from the code (js), map iterates through a collection of values and returns an equivalent to it (morphed result) that is the value returned by the mapper() function. Like a real life map, we are going from starting constructs to another ones ...

Another example is reduce:

    function reduce(x, starting_value, combine) {
      let _internal_initial_value = starting_value;
      for (let element of x) {
        _internal_initial_value = combine(element, _internal_initial_value);
      }
        return _internal_initial_value;
    }
    

Here we are starting with an initial value and in the process we are combining it with other values by applying the combine() function on every element of x. i.e sum = reduce([1, 2, 3], 0, (a, b) => a + b); where (a, b) => a + b is an analogue to a function that takes tow parameters and returns their sum, this type of functions that are created on the fly is called lambda expressions.

The final example is filter:

    function filter(x, predicate) {
      let _internal_filtered_result = [];
      for (let element of x) {
        if (predicate(e)) {
          _internal_filtered_result.push(element);
        }
      }
      
      return _internal_filtered_result;
    }
    

Filter iterates through the values of x and only keeps the ones which the predicate() returns true for them, ones that pass the test.

---------------------------------------
all examples assume that x is an array , x instanceof Array -> true. Still map, reduce and filter can be implemented to any type of collection with ease