Map Filter Reduce

tags: one-dimensional-array map filter reduce

Often you want to traverse one array and perform some operation on each element in the sequence. For example, the following function takes a string as the input and returns a new string that is in upper case.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def upper_case(input)
  letters = input.chars
  
  for i in (0..input.size-1)
    letters[i] = letters[i].upcase
  end
  
  letters.join
end

p upper_case('hello')

An operation like upper_case is called a map because it maps a function (in this case uppercase) onto each of the elements in the sequence.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def upper_only(input)
  letters = input.chars
  result = []
  
  for letter in letters
    if letter == letter.upcase
      result.append(letter)
    end
  end
  
  result
end

p upper_only('HeLlo')

An operation like upper_only is called a filter because it selects some of the elements and filters out the others.

Most common array operations can be expressed as a combination of map, filter and reduce.

Reduce operation is a basic building block that traverses a sequence and accumulates the elements into a single result. An example of reduce is [array sum]({% post_url 2018-11-30-array-sum %})

Map operation is a basic building block that traverses a sequence and performs an operation on each element.

Filter operation is a basic building block that traverses a sequence and selects the elements that satisfy some criterion.