Functional programming should be your # 1 priority in 2015

Original author: Ju Gonçalves
  • Transfer

“The PLO will no longer be able to save us from the Cloud Monsters.”



Translator's note: There are two concepts - parallelism (execution simultaneously, independently) and competitiveness (step-by-step execution, in turn, but at the same time several tasks) and, as always, I had to smash my head by choosing the right terms.

I will duplicate some words or terms in parentheses in the original, in order to search for additional information in English terms, which will be many times more.


You may have heard this expression like: “Clojure”, “Scala”, “Erlang” or even “Java now has lambdas”. And you have, albeit a distant idea of ​​"Functional Programming." If you are a member of any kind of programming community, then this topic could already be discussed by you.

If you search Google for the phrase “Functional Programming,” you won’t see anything new. The second language from the ones created earlier already covers this topic; it was created in the 50s and is called Lisp. Then, what the hell, this topic has become popular just now? Just 60 years later?

In the beginning, computers were very slow



Believe it or not, computers were the most slower than the DOM. No really. And at the same time, there were 2 main ideas in the agreement on the design and implementation of programming languages:




Computers did not have enough computing power to deal with all abstractions and cope with programs written in a functional style. So Lisp was exhausted before, being extremely slow and therefore not suitable for work. It was then that the dominance of the imperative style of programming began, especially with the heyday of C.

But computers have improved a lot.



Now it has become almost normal to use most applications, completely not caring what language they were written in. Functional languages ​​finally got a second chance.

Functional programming 50.5



This article is by no means an introduction to FI. At the end of this section, you will need to know what AF is and how to start your journey of study.

You can understand the term “Functional Programming” too literally as programming using functions and this is not far from the truth. You will create functions in terms of other functions and write functions (Do you remember f ∘ g from the school curriculum? Now it will come in handy). It's all.

The list (not complete) of features of FP:

  1. First-Class Functions
  2. High-Order Functions
  3. Pure Functions
  4. Closures
  5. Immutable State


Now you should not worry about these strange terms, just understand what they mean.

Functions of the first class means that you can save functions in variables. I am sure you did something similar, as in the JavaScript example:

var add = function(a, b){
  return a + b
}

You just created an anonymous function that gets a and b and returns a + b , and assigns this function to the add variable .

Higher-order functions means that functions can return functions or accept functions as parameters.

And again in JavaScript:

document.querySelector('#button')
  .addEventListener('click', function(){
    alert('yay, i got clicked')
  })

or

var add = function(a){
  return function(b){
    return a + b
  }
}
var add2 = add(2)
add2(3) // => 5


Both options are an example of higher-order functions, even if you did not write something like this, you may have seen something similar elsewhere.

Pure functions means that the function does not change the variables, it simply accepts the data and returns the data, like our favorite functions from mathematics. This also means that if you call the function f with argument 2 and it returns 10 , then it will always return 10 . It does not matter what environment, number of threads or order of execution. They do not cause any side effects in other parts of the program and this is a really powerful concept.

Short circuits means that you can save some data inside the function that will be available in a specific return function, in other words, the return function stores its runtime.

var add = function(a){
  return function(b){
    return a + b
  }
}
var add2 = add(2)
add2(3) // => 5

Take a look at the second example from the paragraph Functions of a higher order , the variable a was closed and is available only in the returned function. In fact, closures are not a feature of the FP paradigm, but rather optimization.

An immutable state means that you cannot change any state at all (although you can create new ones). In the following code (on OCaml), you set the variable x to 5 and x will always be 5 .

let x = 5;;
x = 6;;
print_int x;;  (* prints 5 *)


These features look strange enough, but you will soon see how they make your life easier.

Object Oriented Programming Can't Protect You Any More



This is a promising time when we can have distributed and multi-threaded applications, finally arrived. Unfortunately, our existing (or most used) model is not ready for multithreading (concurrency) and parallelism (parallelism), although it solves current problems, it also adds big problems.

To improve applications, we need a simple and reliable way to achieve what we want. Do you remember the above mentioned features of AF? Pure functions and immutable state? That's right, you can perform functions thousands of times on different cores or machines and the result will always be the same. And so, we can run the same code on the same core and on thousands. Life again becomes cloudless.

“But why can't I continue to use OOP?”



At least for multithreading and parallelism, OOP can no longer help you out. Because OOP refers to a state with a mutable state (in imperative languages ​​that are written in OOP style, in most cases). The called methods of the object are supposed to change the current self or this . You will have to make enough effort to correctly update and synchronize all threads.

I’m writing this not to agitate you to switch to FP from the paradigms that you are currently using (although some people will say I should), but you should definitely understand: Java and C ++ 11 already have lambda calculus. I can say that almost all modern and supported languages ​​are going to implement FP features or have already done so.

It is worth noting that we should not stop using mutable state. We must use input / output (IO), etc., so that our programs are useful. The main idea of ​​FP is: use a mutable state only when it is really necessary.

“I do not work with clouds, do I really need to study AF?”



Yes.

Functional Programming will help you write better programs and talk about problems that you have to solve.

"I have tried. It's too complicated and hard to read code. ”



Starting is always difficult in any field. I am sure you started to learn programming also having a bunch of problems, even in OOP languages. Maybe starting to write in OOP style was easier than writing your first program because you already knew some common idioms, like declaring variables and for / while loops.

To start learning FP is almost the same as starting to write programs from scratch again (no matter what language you started to learn, it will be unambiguous how to start from the very beginning).

Many may note that AF is difficult to read. If you have experience in imperative languages, functional programs will look like cryptography. And not because this is true, but because you do not know its main idioms. Once, having understood the fundamental principles, programs will become much more readable.

Check out the program written in Haskell and JavaScript (imperative style):

guess :: Int -> [Char]
guess 7 = "Much 7 very wow."
guess x = "Ooops, try again."
-- strongly inspired by http://learnyouahaskell.com

function guess(x){
  if(x == 7){
    return "Much 7 very wow."
  }
  else {
    return "Oops, try again."
  }
}

This is a very simple program. It displays a congratulatory message when the user guessed and entered the number 7 or displays an error message in all other cases. Perhaps this looks like encryption, as Haskell can do all the work in just two lines of code (you can ignore the first line, it's just a "type declaration"). But it will become quite simple, once, having understood the possibilities of pattern matching (which are implemented not only in FP languages, but were their feature).

What Haskell does:

If the accepted argument of guess is 7, then it will return “Much 7 very wow.” Or it will return “Oooops, try again.” In other cases.

And this is the same thing that JavaScript code does, but Haskell maps to the "pattern" declared by the programmer in the code.

This approach may not seem very useful in this case, if you can use if / else. But it will become really useful when you yourself begin to write more complex data structures.

plus1 :: [Int] -> [Int]
plus1 []      = []
plus1 (x:xs)  = x + 1 : plus1 xs 
-- plus1 [0,1,2,3]
-- > [1,2,3,4]

In the program above, * plus1 * is a function that takes a list of integers and adds 1 to each element of the list. The function compares when the list is empty [] (returns another empty list, since there are no elements in it) bypasses the non-empty list and defines a pattern of matching: x as the first element of the list, xs as the remaining list. Then it simply calculates the sum and combines it through a recursive call.

I am sure you will spend many minutes (not the most pleasant), rewriting this example in an imperative style, fitting the code in two lines, while maintaining readability.

So let's get started



A lot of material on Functional Programming has been published, but you should not skip these links unambiguously:

  1. Principles of Functional Programming in Scala : the course will be useful for those who know Java and want to try Functional Programming without jumping from the JVM. The course covers basic concepts.
  2. Paradigms of Computer Programming - Fundamentals : this course will be useful for those who want to learn how to write programs in a functional language. The course uses the Qz learning language. There are a lot of exercises in the course, you can use a functional language and try to create your own data structure. I suppose the course provides building blocks for the “building” called “Functional Programming”, it will help you with other languages ​​in the future.


Unfortunately, courses will only be available at the end of the year. But you can follow the content and videos, they are available on Youtube.

On the other hand, if you prefer text materials, I certainly recommend some of them:

  1. Structure and Interpretation of Computer Programs
  2. How to Design Programs
  3. Concepts, Techniques, and Models of Computer Programming


The first two have similar curricula, introduce you to the basis of Functional Programming and are very suitable for beginners. The third of the links, this course of the Paradigm of Computer Programming, covers more than Functional Programming. It is important to note that these materials are for entry level.

In addition, Chris Allen wrote an excellent article on the study of Functional Programming. It is called Functional Education.and has an exhaustive list of materials for learning Functional Programming using Haskell, as well as talks about the strengths and weaknesses of this approach. Following the links recommended by Chris, you can learn the basic principles and more complex topics (I’m sure you heard about monads) of Functional Programming and perhaps you will understand how to write applications using them. (Thank you Chris for the links to the materials.)

Good luck with your Functional New Year! ☺

Also popular now: