The beauty of Functional Programming
Fanny

Fanny @fannyvieira

About: Master of none & passionate by computer challenges.

Joined:
May 7, 2017

The beauty of Functional Programming

Publish Date: Dec 26 '19
650 34

There are many ways to make a program, probably you already made your program like a serie of commands, this is what we called of "imperative programming" or maybe you do your program keeping things in objects and interacting with them sending messages back and forward, this is "object oriented programming", but today i'll talk about Functional Programming, like the others mentionated, functional programming is a coding style, this is not about put or not ; or put {} after or below the expressions, but it's how we can instruct the program to make the things, in a technical way this is a "programming paradigm". So why you should care about this?

Fun Fun Functions ✨

When we talk about the world of functional programming, everything are functions. And the concept is too similar the math concept, when we study at school, the teacher says something like:

A function is a special relationship between values: Each of its input values gives back exactly one output value

from mathisfun

This definition is really important because give us the basis of our programs, called pure functions, pure functions are functions that only depends of its inputs, they don't look for anything else outside of your world, expect the arguments that you passed through, and only returns the output, they don't affect oher part of world. For example, see these functions, you can say what's wrong with the first?

First version ❌


let age = 19

function getMyAge() {
  console.log(`I'm ${age} years old.`)
}

getMyAge(age)
age = 20
getMyAge(age)
Enter fullscreen mode Exit fullscreen mode

Second Version ✅

function getMyAge(age) {
  return `I'm ${age} years old.`
}

getMyAge(19)
getMyAge(20)
Enter fullscreen mode Exit fullscreen mode

In the first case, the function is looking for a variable outside of your scope, changing the world of some way, in this case the output, the ideal is only return the value and if as you noticed, if we call the function, with same argument(even there's no argument), we get it a different value. In a pure function this is not happen.
Now, you have a basic idea of good things provided by functional programming, but we have more, check it out below our abilities 💪.

Side Effects 🌊

A side effect is any interaction with our outside world that occurs during the calculations, that don't happen using pure functions, and our code, can be more predictale, because our results only depends its inputs, if we know what the function looks like, and which inputs it receives, you can predict the result..

Mutability 🐺

Mutability is about things changeable, here in func. programming the mutability is discouranged. When we have immutable data, its state cannot change after you created, if you need change something, you need create a new value.

Mutable example

function changeFirstElem(array) {
  array[0] = 'Lose yourself to dance'
}

const daftPunkPopSongs = ['Instant Crush', 'Get Lucky', 'One More Time']
changeFirstElem(daftPunkPopSongs)
Enter fullscreen mode Exit fullscreen mode

Immutable example

function changeFirstElem(array) {
  const modifiedArray = ['Lose yourself to dance', ...array]
  return modifiedArray
}

const daftPunkPopSongs = ['Instant Crush', 'Get Lucky', 'One More Time']
const modifiedArray = changeFirstElem(daftPunkPopSongs)

Enter fullscreen mode Exit fullscreen mode

This is awesome, because we make the things more safer, its harder do introduce bugs in our code, also means that is easier to test/debug our code. It's because the one thing that we need to know is about the output, follow the params, and if the output is wrong, we're sure that the problem is our function and not because a random interaction.

Recursion 🥞

Recursion is a technique, in that we can solve a problem in small pieces, this help us to avoid some side effects when we use interactions.

function myCount(int i) {
  if(i >= 10) return 0
  else return i + myCount(i+1)
}
myCount(1);
Enter fullscreen mode Exit fullscreen mode

For me, the recursion makes a code more declarative, more readable and cleaner, although in many scenarios i prefer using iterative way.

The super heroes of Functional Programming 🧚‍♀️

Beyond the recursion, we have tree functions that help us to manipulate the data they are map-filter-reducer. In JS, functions also treated as values, since that, we can pass it a parameter to other functions.

Map, given a collection of data, you can pass a function to transform each item.

const numbers = [1, 2, 3];
const doubles = numbers.map(num => num * 2) //[2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Filter receives a collection of data, and you can pass a conditional function that returns a subset of collection.

const numbers = [1, 2, 3];
const isGreaterThanOne = numbers.filter(num => num > 1) //[2, 3]
Enter fullscreen mode Exit fullscreen mode

And finally, Reduce, given a collection of data you can reduce to a single value.

const numbers = [1, 2, 3];
const mySum = numbers.reduce((accumulator, num) => accumulator + num) //6
Enter fullscreen mode Exit fullscreen mode

Conclusion 💃

I'm beginning on the study of functional programming, and these things motivates me to start and keep seeing many resources, obviously, functional programming has weakness, but now that's not the point. If you need other resources i'll left some below, enjoy and have-fun!

Books

Hackernoon - Understanding Functional Programming
Professor Frisby's Mostly Adequate Guide to Functional Programming
Functional JavaScript Mini Book by Jichao Ouyang
Pragmatic Function Javascript online book

Talks

Anjana Vankil - Functional Programming: What? Why? How?One of my favourites
Anjana Vankil - Immutable data structures for functional JS
Fun Fun Function Series

Comments 34 total

  • Jan Melicherik
    Jan MelicherikDec 26, 2019

    Great article to encourage ppl About functional program Ing. Thx a lot

    • Fanny
      FannyDec 26, 2019

      Thanks <3

  • Heiker
    HeikerDec 26, 2019

    Another important thing that functional programming encourage is function composition. Even the most simple function can be useful if you combine it with something else.

    This is one example that I really like. Say that you have this function.

    function identity(arg) {
      return arg;
    }
    

    It may seen useless but if you have map function that works like Array.map but for "plain" objects, you could implement a shallow_copy function like this.

    function shallow_copy(obj){
      return map(identity, obj);
    }
    
    • Fanny
      FannyDec 26, 2019

      Yes, this is a nice example, I agree. And i will explain more about this, in the next posts

  • АнонимDec 26, 2019

    [deleted]

    • Emil Koutanov
      Emil KoutanovDec 27, 2019

      Sorry Fanny, but it would be classed as a pure function in spite of writing to a local variable. As long as the write has no side effects that are externally observable, it would satisfy the definition of a pure function.

      Even a recursive function with no visible variable assignment may introduce any number of intermediate variables as part of compiler optimisation; this wouldn't make it any less pure provided these changes did not escape outside function scope.

  • Fanny
    FannyDec 26, 2019

    Because it is performing a side effect, by definition, can you write me a example using interation that you agree that is a impure function?

  • Lucis
    LucisDec 27, 2019

    Really nice post, Fanny!

    The most cool thing about learning FP, in my opinion, is that it makes you a better developer as a hole, even when programming using other paradigms. Composition, avoiding state mutations, writing small and efective functions will all help you avoid common pitfalls when coding.

    There's a cool article from Paul Graham, a famous entrepreneur and programmer, that he talks about the importance of LISP, the first FP language, in his startup years ago.

    I would advise you to practice such skills using a "more functional" programming language, it's a nice exercise. There are three that I like: ReasonML (blends well with React), F# (being .NET is a pro, and it's really good when modeling a domain) and Clojure (super bright community, and made by some awesome developers. Used by Nubank).

  • pthreat
    pthreatDec 27, 2019

    Agreed

    • Ivan Pierre
      Ivan PierreApr 9, 2020

      result is an external state, initialized outside the function. myCount() will give a different response, every time you call it. There's a side effect on i inside the loop.
      That's anything except a pure function.

      Pure function:

      • Its return value is the same for the same arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams from I/O devices).
      • Its evaluation has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or I/O streams).
  • Tony Tin Nguyen
    Tony Tin NguyenDec 27, 2019

    Thanks Fanny for informative explanation.

    • Fanny
      FannyDec 27, 2019

      Thank you <3

  • AbdRozaq
    AbdRozaqDec 27, 2019

    Great write up, and I was looking out for the buzz word "passing functions as variables" as this helped me grasp the concept long ago.

  • Chris Knight
    Chris KnightDec 27, 2019

    I agree. I doubt many people would consider the recursive version to be more readable in this case. Recursion is a very powerful tool which is essential in some scenarios and just plain more elegant and understandable in others. However, here it really is unnecessary. Recursive code can also be extremely difficult to debug. This is my own personal experience from working a lot with trees in several different contexts.

  • Roland Csibrei
    Roland CsibreiDec 27, 2019

    With a few mistakes (changeFirstElement in the immutable data example will ADD a record to the first position, index zero, and not change it) but a good article for the beginners to understand, why is fn programming and immutability so cool. Thx!

  • Fanny
    FannyDec 27, 2019

    Hi Marcelo, this is because the idea is show that you need create a new array in immutable data, and not only change a array element ;)

  • Fanny
    FannyDec 27, 2019

    Good suggestion,thanks

    • Gabriel Garcia
      Gabriel GarciaDec 27, 2019

      Another option is

      function what([x, ...xs]) {
        return ['new first elem', ...xs];
      }
      
  • Gabriel Garcia
    Gabriel GarciaDec 27, 2019

    Hi Fanny! Keep it up! I'm glad to see FP being introduced in different languages

  • João Paulo dos Santos Portela
    João Paulo dos Santos PortelaDec 27, 2019

    There's just this a tiny little thing that you missed:

    Where you have:

    const numbers = [1, 2, 3];
    const doubles = numbers.map(num => num * 2) //[1, 4, 6]
    

    It should be:

    const numbers = [1, 2, 3];
    const doubles = numbers.map(num => num * 2) //[2, 4, 6]
    

    (notice the comment change)

  • Fanny
    FannyDec 27, 2019

    Okay, i agree partially with you, because for many friends is confuse the syntax of the loop reassigning the count value many times
    i = i+1, and the math perspective this is dont make sense, in recursive way this is declarative, you express what you want and the recursion make the things, although in many scenarios i prefer using iterative way. Since this is my particular opinion and the example was too confuse, i removed. But yes, with recursion we have other problems

  • Fernando Abreu
    Fernando AbreuDec 27, 2019

    I'm a functional programmer myself, as much as possible. Nice reading your article!

  • Sanousy
    SanousyDec 27, 2019

    Nice article, actually I was going the counter direction, to make C go object oriented

    github.com/sanousy/cplus

  • aRtoo
    aRtooDec 27, 2019

    Theres a book that ive read that you dont have to force yourself to use recursion because its prone to SO error, like if a base case is not correctly enforced. Although recursion is useful for sorting and tress. nice article btw. :)

  • Alan
    AlanDec 28, 2019

    These are great. Though you missed one best virtue of FP, the Type System. It's hard to do in js though as js doesn't have any explicit compilation step and compile time type at all.

    Check this out dev.to/wolksoftware/why-typescript...

  • taha HTEWECH
    taha HTEWECHJan 1, 2020

    Thanks Fanny, i am new in programming and this article was awsome

  • Linda Zhou
    Linda ZhouJan 22, 2020

    Glad to see functional programming is having a bit of a renaissance :)

Add comment