FPF #1: Functional Programming Fridays!

Bryan Gilbraith
5 min readOct 14, 2016

--

Welcome to Functional Programming Fridays!

(Intro — FPF#0 can be found here)

Okay, here we are. We just decided to take some steps to become more functional programmers. Where do we begin? I suppose we start from the top.

The basics:

Wikipedia says:

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.

…wat?

Basically, a functional design pattern should:

1. Be pure functions.

Given the same input, we should expect the same output. For example, this is a pure function:

function add5(x) {
return x + 5
}

Every time we call add5(10), we get 15.

This on the other hand, is impure.

let count = 5
function addCount(x) {
return count + x
}

If we call addCount(10), we will get 15. Great! But what happens when someOtherFunction comes along and messes with our variable?

someOtherFunction(spud) {
...
count = spud
}

Now when we run addCount(10), suddenly our program spits out 'potato10'. That is drastically different from the 15 we were expecting. We, as human programmers, should be able to reason about our code (if you are a robot programmer from the future, I’m not excluding you. I’m sorry if I have offended you, kind and loving Robot Overlords! Hail!).

It gets complicated trying to keep track of variables that too many other functions touch. Tell those other functions we don’t want their stupid germs, and to stay off our pure function’s lawn. But don’t be rude to the functions, because unlike some other languages:

2. Functions are first class citizens.

This is how everyone explains it when they write about functional programming. Basically, it means that you can take that function, save it into a variable, and pass it around. You can use it as an argument for another function, or you can return it from another function (which is how currying and composing functions work. We’ll talk about that in a later post). As a programmer who came on the scene with Javascript, this seemed like no big deal to me, because that’s how I’ve pretty much always known them. If you are coming from some other language, this might not be as clear. Because of the way Javascript treats functions, I can do this:

let person = function(name) { 
return function(mood) {
return `${name} is dancin' cause they're ${mood}!`
}
}
//internet points for proper they're use, plz.

Now I can make you and I! Let’s dance!

let bryan = person(‘Bryan’)
let stranger = person('Internet Stranger')
bryan('happy') //"Bryan is dancin' cause they're happy!"
stranger('learning about closures') //"Internet Stranger is dancin' cause they're learning about closures"

See what I did there? I secretly taught you a little bit about closures. The reason composing these functions works is because of closures — the inner function never loses access to the outer functions arguments. Thats why we can use ${name} in the inner function as well as the outer! Without this superpower, none of this would be possible.

The last bit I want to talk about in this first post is all about…

3. Immutable data.

The reason the second point came so easily to me is the same reason this one took a bit longer to see the importance of. In Javascript, you can mutate data any way you like. Check out this nice little array down there. Wow!

let arr = [1,2,3,4,5] 

Neat! But suddenly….

Wild Rattata appeared!
arr.push('rattata')console.log(arr) // [1, 2, 3, 4, 5, 'rattata']

So now, not only is the Rattata just a stupid lvl 2, our original array is not what we intended it to be. I’m not sure what you’re doing with your arrays, but that unintended effect is likely to screw it up. For example, say the whole point of your array was to double your numbers, suddenly you have this ugly NaN to deal with. All because we mutated something inappropriately.

arr.map(num => num * 2)// [2, 4, 6, 8, 10, NaN]

Ew.

This kind of ties back in to our first point well. We should be able to look at a function, and expect the correct output. The more chances we give our functions to change things, the higher the risk we take of inviting unexpected changes in, and possibly breaking our beautiful programs.

But what if for some reason, we actually want Rattata there?

let arr = [1,2,3,4,5]
function plusRattata(array) {
return array.concat('Rattata')
}
let arrWithRattata = plusRattata(arr) console.log(arr) // [1, 2, 3, 4, 5]
console.log(arrWithRattata) //[1, 2, 3, 4, 5, 'Rattata']

Just like that, all the pieces that rely on our array containing only numbers still work, and the ones that need one of the worst Pokemon of them all at the end can still do whatever it needs to do.

Okay, so there’s a bit to get us started. Next week, I want to talk about Recursion, some helpful built in functions like Array#map/reduce/filter and we will get in to some fun problems! For now, I will leave you with a few links to get started with, and a few problems to solve. Try to use what we talked about above on the problems below. I would love to hear how you would go about solving these, so feel free to comment on this post or hit me up on twitter @spacebrayn with your questions, solutions, life goals, deepest fears, or any cute giraffe pictures. Seriously though, pls send cute giraffe pics.

// 1. Write a program that takes an array and returns every other item  function everyOther(array) {
... your code here
//(hint: perhaps look in to Array#filter)
}
// 2. Write a function that returns another function. This one is as freeform as you want it to be! function returnF(input) {
...your code here
}
// 3. Write a program that prints out the numbers 0 through x on the screen WITHOUT using loops! function printNumbers(x) {
...your code here
//(hint: look into recursion)
}

Read (we’ll talk about it next time):

  1. MDN — Array#Filter
  2. MDN — Array#Map
  3. MDN — Array#Reduce
  4. MDN — Functions and Recursion
  5. XKCD — Vodka

Thanks friends! Till next time!

❤ Bryan.

--

--

Bryan Gilbraith

I like programming and video games and my dog and run on sentences. Oh yeah, and I think you’re neat ❤