What is functional programming?
Good question! I like people who are curious and ask. Quoting Wikipedia here:
In computer science, functional programming is a programming paradigm — a style of building the structure and elements of computer programs — that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
Wow. Look how much that definition helped. Well, let’s take a deep breath and reword it. Functional programming, in essence, is one of the many ways of writing code (remember procedural paradigm?.) A specific model, or say a set of rules that we define while creating the language and writing code with it.
The paradigm reads calculations as the results of mathematical function i.e given some input parameters , the output for those parameters will always be the same. This paradigm also emphasizes heavily on immutability — data that can not be changed at a later state.
Let’s get started, maybe?
Functional programming has a steep learning curve. For some, it might get take more time but you’ll get there.
In this snippet, the function printElement() takes in a variable and logs it onto the console. The function, doSomething() accepts a function and a datatype and then plugs in the data with the function it just accepted. So we can define as many new functions we want and call doSomething() to run that function for us. Amazing, right? Oh so you want me to show it you don’t you?
Higher Order functions vs Functions as First class objects?
I was really confused between the two concepts. Let‘s see the amazing doSomething() function again. It accepts a function, someAction() and then returns it with the completed result of someAction() and element. That is a true mark of a higher order function (your ancestor higher order functions would be so proud of you doSomething().) But in this article, I am calling it a first class function. Now there must be some relation between these two concepts, right?
This Stack Overflow answer by Haskell expert and author, Don Stewart explains the relation perfectly.
They're different. First class functions Values in a language that are handled uniformly throughout are called "first…stackoverflow.com
To paraphrase, higher order functions are a consequence of making functions as first class i.e functions should be treated just like other objects, arrays, floats etc.
Wrapping up Part 1
So where are we? We learned what functional languages are. It is a new way to write code with different features than procedural languages. Functions in functional languages are first-class objects and computations are interpreted as mathematical functions. For a set of input the output will always be the same. We also learned that data types in these languages are immutable. More on that in part 2.