In order to talk about higher order functions and how to use them we should first understand what a higher order function is. This blog will go over briefly what a higher order function actually is, reasons they can be very useful and a couple highly used ones and how to use them. Hopefully by the end of reading this blog, the reader will be slightly more informed on the usage and origin of not only higher order functions but functions in general.
Higher order functions are more simple than some people might realize. They are simply functions that either take in functions as parameters, return functions as results or both. This might be a bit difficult to wrap ones head around but it might be easier to think of using a function like any other data type. Jumping into an example might make explaining easier.
array = [1, 2, 3, 4, 5]
def print_nums(a)
a.each do |element|
puts element + 1
end
end
print_nums(array)
In this example we are working with the "each" higher order function. What this function does is it will do some work on each element of an array. In this example we use a simple array of the numbers 1 through 5. The parameter that we have here is the letter a, and the argument we pass into the print_nums call is the array called array. What each will do is that it will pass over every element inside its passed in array and do some sort of work on it. In this case, it will put out(print, console.log) each of these numbers + 1, for every number.
2
3
4
5
6
=> [1, 2, 3, 4, 5]
This is our output. If we notice here each prints out each elements value + 1. BUT its return value is the original array. This is because using each we do not mutate the original array. However, as with most if not all non mutable functions we can simply set a container variable and hold what work is being done behind the scenes and just return that.
array = [1, 2, 3, 4, 5]
def print_nums(a)
new_array = [] #container
a.each do |element|
new_array << element + 1 #push into new array
end
new_array #return
end
print_nums(array)
This will give us:
=> [2, 3, 4, 5, 6]
If you were not aware, the => means return value, otherwise it is merely a log or a print.
So thats cool, but there is actually a better way to do this particular example. A useful higher order function that works with arrays is one called "map". Map will go through each element in the array, do the work, and then return a new array automatically with the work done.
array = [1, 2, 3, 4, 5]
def print_nums(a)
a.map do |element| element + 1
end
end
print_nums(array)
Output:
=> [2, 3, 4, 5, 6]
These are highly used iterators. Which for anyone who is possibly unaware just means to do something repeatedly. Iterators, of course, are extremely useful with arrays. There are many useful higher order functions but anyone in the programming world will undoubtedly be using these at some point in their careers.
Top comments (0)