FPiS – Tail Recursion and Higher-Order-Functions

Canva - Tail of whale above water.jpg

Overview

Chapter 2 of Functional Programming in Scala starts by giving some basic syntax and understanding of the Scala language.  Since my main focus in studying this book is to sharpen my ability to think functionally, I will not write much about Scala here.  This chapter also covered Tail Recursion and Higher-Order Functions.

Tail Recursion

I remember during my undergraduate work particularly struggling with recursion.  Of course almost everything I was learning with respect to software was new to me at that time.  Even today, however, I still feel like I have to exercise the neurons in new ways to think recursively.   As I have studied Functional Programming, my recursive chops have grown considerably – and I have enjoyed the elegant solutions that recursion allows.

A tail call refers to the recursive call in a function, when no additional operation needs to be performed on the returned value.  When this is the case, the Scala compiler turns the recursion into a loop.  This allows the developer to use a recursive solution without fear of blowing the stack.

Higher-Order Function

Another topic discussed in this chapter are Higher-Order Functions.  An HOF is a function that takes as a parameter another function.  Take for example, the function definition below.  The function sort takes as a parameter an array of integers and a function of type (Int, Int) to Boolean.  That is, sort will accept a function that takes as a parameters two integers and returns a boolean (i.e. a comparison function). In this case, sort is a Higher-Order Function.

def sort(a: Array[Int], f: (Int, Int) => Boolean): Array[Int]

Conclusion

My solutions to the exercises from Chapter 2 can be found on GitHub.  If you have any corrections for my definitions above, please drop a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s