• So You Want to be a Functional Programmer (Part 6)
  • The Nuggets translation Project
  • Translator: DeadLion
  • Proofreader: Cyseria, luoyaqifei

Ready to learn functional programming? (Part 6)

The first step, understanding functional programming concepts, is the most important, but also the most difficult. It doesn’t have to be that difficult if you come at it from the right Angle or approach.

Review the previous parts: Part 1, Part 2, Part 3, Part 4, Part 5

What to do now?

Now that you’ve learned all these new things, you’re probably wondering, “What now? How do I use it in everyday programming?”

It depends. If you know how to program in a purely functional language like Elm or Haskell, you can try all of these ideas. These languages make it easy to implement these ideas.

If you only know how to program in imperative languages like Javascript (and most of us certainly do), you can still use a lot of what you’ve learned, but it takes a lot more training.

Javascript function type

Javascript has many features that allow you to program in an almost functional manner. It’s not purely functional, but you can get invariance from the language, even more libraries.

It’s not optimal, but if you have to use it, why not take advantage of some of the advantages of functional languages?

invariance

The first thing to consider is immutability. In ES2015, or ES6, because it has a new keyword called constant. This means that once a variable is set, it cannot be modified:

const a = 1;
a = 2; // this will throw a TypeError in Chrome, Firefox or Node
       // but not in Safari (circa 10/2016)
Copy the code

Here a is defined as a constant, meaning that it cannot be changed once assigned. That’s why a = 2 throws an exception (except Safari).

The problem with Javascript constants is that they don’t go far enough. The following example illustrates its limitations:

const a = {
    x: 1,
    y: 2
};
a.x = 2; // NO EXCEPTION!
a = {}; // this will throw a TypeError
Copy the code

Note that a.x = 2 does not throw an exception. The invariance of the const keyword applies only to the variable A. Any variable that a points to can change.

This is very disappointing because it could have made Javascript better.

So how do we get immutability from Javascript?

Unfortunately, we can only do this through a library called Immutable. This may give us better immutability, but sadly, the way it’s implemented makes our code look more like Java.

Currization and composition

In previous articles in this series, we learned how to write the coriolization functionality. Here’s a more complicated example:

const f = a => b => c => d => a + b + c + d
Copy the code

Note that we had to write the Corrification part by hand.

To call f, we must write:

console.log(f(1)(2)(3)(4)); // prints 10
Copy the code

But there are enough parentheses to make Lisp programmers cry! Lisp statements use a lot of parentheses.

There are many libraries that can simplify this process. One of my favorites is Ramda.

With Ramda we can write like this:

const f = R.curry((a, b, c, d) => a + b + c + d); console.log(f(1, 2, 3, 4)); // Print 10 console.log(f(1, 2)(3, 4)); // Also prints 10 console.log(f(1)(2)(3, 4)); // Also print 10Copy the code

The function definition hasn’t improved much, but we’ve eliminated the need for all parentheses. Note that we can apply as many arguments as we do each time we call f.

With Ramda, we can rewrite Part 3 and Part 4 mult5AfterAdd10 functionality:

const add = R.curry((x, y) => x + y);
const mult5 = value => value * 5;
const mult5AfterAdd10 = R.compose(mult5, add(10));
Copy the code

As it turns out, Ramda has a lot of helper functions to do these things, for example. R.dd and R.ply, which means we can write less code:

const mult5AfterAdd10 = R.compose(R.multiply(5), R.add(10));
Copy the code

Map, Filter and Reduce

Ramda also has its own Map, Filter, and Reduce. Although these features already exist in normal Javascript Array.prototype, the Ramda version has more features:

const isOdd = R.flip(R.modulo)(2);
const onlyOdd = R.filter(isOdd);
const isEven = R.complement(isOdd);
const onlyEven = R.filter(isEven);

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(onlyEven(numbers)); // prints [2, 4, 6, 8]
console.log(onlyOdd(numbers)); // prints [1, 3, 5, 7]
Copy the code

R.m Odulo takes two arguments. The first argument is dividend, and the second argument is divisor.

IsOdd is just dividing by the remainder of 2. A remainder of 0 is falsy, not odd, and a remainder of 1 is Truthy, odd. We flip the first and second arguments of modulo so that we can specify 2 as the divisor.

The isEven function is just a complement of isOdd.

The onlyOdd function is a filter that is asserted by isOdd (returning only Boolean methods). It’s waiting for the numbers array, the last argument it needs before it executes.

The onlyEven is a filter that uses isEven to assert.

When we pass numbers to the onlyEven, onlyOdd, isEven, and isOdd methods, we get their final arguments, execute them, and return the result we expect.

Javascript shortcomings

Javascript now has many libraries and the language has been enhanced, but it still has to face the harsh reality that it is an imperative language that seems to be able to do anything.

Most front-end people use Javascript in their browsers all the time because it’s always been the only option. But now many developers are moving away from writing Javascript directly.

Instead, they write and compile in a different language, or more precisely, convert to Javascript in another language.

CoffeeScript is the first of these languages. Today, Typescript is available in Angular 2. Babel is also a Javascript conversion compiler.

More and more people are adopting this approach for production environments.

But these languages are still based on Javascript, and only slightly improved. Why not switch from a purely functional language to Javascript?

Elm

In this series, we learned about Elm to help understand functional programming.

But what is Elm? What am I supposed to do with it?

Elm is a purely functional programming language, eventually compiled into Javascript, so you can use it to create Web applications using The Elm Architecture, or TEA (The Architecture that inspired The developers of Redux).

The Elm program does not have any runtime errors.

Companies like NoRedInk have used Elm in production environments, and Elm’s creator Evan Czapliki now works for the company (he previously worked at Prezi).

Check out this interview, 6 months on Elm in production environment, by Richard Feldman from NoRedInk and Elm evangelist.

Do I need to replace all my Javascript with Elm?

No, you can replace it gradually. Check out this article How to Use Elm at Work to learn more.

Why learn Elm?

  1. Functional programming is both restrictive and free. It limits what you can do (mostly to make sure you don’t “accidentally fire” yourself), but it also protects you from bugs and bad design decisions, because all Elm programs follow Elm Architecture, a functional responsive programming model.
  2. Functional programming can make you a better programmer. The ideas in this article are just the tip of the iceberg. You really need to see in practice how they make your programs smaller and more stable.
  3. Javascript was originally built in 10 days and then tinkered with over the past two decades to become a somewhat functional, somewhat object-oriented, and completely imperative programming language. The design of Elm draws on the knowledge of the Haskell community over the past 30 years of work, as well as decades of experience in mathematics and computer science. Elm Architecture (TEA) was designed and refined over many years and is the result of Evan’s paper on functional responsive programming. Take a look at Controlling Time and Space to understand the concept of this design.
  4. Elm is designed for front-end Web developers. It is designed to make their jobs easier. To better understand this goal, watch Let’s Be Mainstream.

In the future

It’s impossible to know what the future holds, but we can make some guesses. Here are some of mine:

An unambiguous language will appear, compiled into Javascript.

Functional programming ideas that have existed for more than 40 years will be rediscovered to solve current software complexity problems.

The state of the hardware, such as gigabytes of cheap memory and fast processors, will make functional techniques feasible.

Cpus won’t get faster, but the number of cores will continue to grow.

Mutable state will be one of the biggest problems in complex systems.

I’m writing this series because I believe that the future is functional programming, and I’ve spent the last few years trying to learn it (I’m still learning it).

My goal is to help others learn these concepts more easily and faster than I did, and to help others become better programmers so that they can have better job prospects in the future.

Even if I was wrong in predicting that Elm would be a great language in the future, I can say for sure that functional programming and Elm will make a big mark on the picture.

I hope that after reading this series you will feel more confident in your abilities and understanding of these concepts.

Good luck in your future work.

If you want to join a community of Web developers to learn and help each other develop Web applications using Elm functional programming, join my Facebook Group, Learn Elm Programmingwww.facebook.com/groups/lear…