Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Functional Programming #6

Open
noobling opened this issue Dec 4, 2018 · 0 comments
Open

Functional Programming #6

noobling opened this issue Dec 4, 2018 · 0 comments

Comments

@noobling
Copy link
Owner

noobling commented Dec 4, 2018

Functional trend came from lambda calculus. Functions have since been a part of calculus since it emerged in the 17th century. More complex functions are called higher-order functions.

In 1950s, John McCarthy took concepts from lambda calculus and applied them to a new programming language called Lisp. Lisp implemented the concept of higher-order functions and functions as first-class members or first-class citizens. A function is said to be a first-class citizen when it can be declared as a variable and sent to functions as an argument. These functions can be returned from functions.

Functional programs prefer recursion over loops because they have to since they cannot alter the state and have no side effects. Not having side effects means you cannot have loop counters since they constitute a mutable state. In recursion no state is needed so this is a natural match for recursion. Having no side effects also means that the compiler can optimise it better with tail call optimisation.

Higher-order functions

When a function returns or takes in other functions it is said to be a higher-order function

var createScream = function(logger) { 
            return function(message) {
            logger(message.toUpperCase() + "!!!")
        }
}

const scream = createScream(message => console.log(message))
scream('functions can be returned from other functions')
scream('createScream returns a function')
scream('scream invokes that returned function')
// FUNCTIONS CAN BE RETURNED FROM OTHER FUNCTIONS!!!
// CREATESCREAM RETURNS A FUNCTION!!!
// SCREAM INVOKES THAT RETURNED FUNCTION!!!

We can write it with arrow function as well.

createScream = logger => message => logger(message.toUpperCase() + "!!!")

Declarative vs Imperative programming

Functional programming is part of a larger programming paradigm called declarative programming.

Declarative programming focuses on what is supposed to happen whereas imperative programming focuses on how the task is achieved e.g. Implementation level.

///////////////// Imperative
var string = "This is the midday show with Cheryl Waters"; 
var urlFriendly = "";
for (var i=0; i<string.length; i++) { 
  if (string[i] === " ") {
    urlFriendly += "-"; 
  } else {
    urlFriendly += string[i];
  }
}
console.log(urlFriendly);

///////////////// Declarative
const urlFriendly = string.replace(/ /g, '-')

We can see declarative is higher level compared to imperative.

Immutability

Data is immutable in functional/declarative programming

let color_lawn = { 
  title: "lawn",
  color: "#00FF00",
  rating: 0 
}

////////////// Mutating the object
function rateColor(color, rating) { color.rating = rating
  return color
}
console.log(rateColor(color_lawn, 5).rating)
console.log(color_lawn.rating)

///////////// Functional Programming not mutating object

var rateColor = function(color, rating) {
  return Object.assign({}, color, {rating:rating})
}
console.log(rateColor(color_lawn, 5).rating) // 5
console.log(color_lawn.rating) // 4

///////////// No mutating using latest JS
const rateColor = (color, rating) => ({...color, rating})

//////////// Use functions that don't mutate data for example Array.push mutates use Array.concat or spread operator

Pure Functions

Pure functions Return a value based on the parameter passed in. They do not change the application state e.g. no side effects, set global variables. The advantage of these sort of functions are that they are easily testable and don't require a complicated setup. The output is also easier to predict. In React UI is expressed with pure functions e.g. const header = (props) => <h1>{props.title}</h1>

Most useful functions in JS (imo)

  • map
  • filter
  • join
  • reduce (Reduce array to a single value using some condition)

More examples of writing pure functions

//////////// Editing a certain value without altering original object
let schools = [
{ name: "Yorktown"},
{ name: "Stratford" },
{ name: "Washington & Lee"}, { name: "Wakefield"}
]

const editNames = (oldName, name, schools) =>
  schools.map(school => school.name === oldName ?
    ({...school, name}) : school)

The ({...school, name}) is an interesting line what it means is expand the object school and replace all name attributes with the value held by the name parameter passed in. Not the parenthesis they need to be there in order to return an object literal (I think)

Making an array with only distinct values

const colors = ['red', 'red', 'green', 'blue', 'green']

const distinctColors = colors.reduce(
  (distinct, color) =>
    (distinct.indexOf(color) !== -1) ?
       distinct :
       [... distinct, color],
  []
)

Composition

You should break the program up into small pure functions that are focused on specific tasks and eventually you will need to put these smaller functions together on example is chaining functions together.

Making an object immutable

import deepFreeze from 'deep-freeze'

deepFreeze(obj)

Source

Learning React

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant