pianomanfrazier / functional-programming-intro

Some code examples and explanation of function programming (FP)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Key Ideas to Functional Programming

You build up your program with functions. You can organize functions into modules.

A function is a reliable black box with explicit inputs and outputs. Everytime you put the same input into the function you get the exact same output. This is the mathematical definition of a function.

In mathematics, a function is a binary relation over two sets that associates to every element of the first set exactly one element of the second set.

Wikipedia, Function (mathematics) --- https://en.wikipedia.org/wiki/Function_(mathematics)

Function color example 3

Function vs. Procedure

Most of the time when we talk about functions in our code they are probably not functions in the mathematical sense. They are more accurately called procedures. A chunk of code that does something. There are no guarantees that the chunk of code behaves like a mathematical function (i.e. maps values from one set to another).

Vocabulary

  • functional purity
  • referential transparency
  • side effect
  • monad
  • algebraic data type (ADT)
  • declarative, imperative, procedural, structural
  • reactive

No for loops

Most of the time when you see a for loop what you really want is filter, map, or reduce. You "declare" what you want instead of telling the computer how to do it.

const things = [1,2,3,4]
const target = 2

// find element
let foundItem = null
for (const element of things) {
    if (element === target) {
        foundItem = element
        break
    }
}
const result = things.filter(x => x === target) // result[0] === target

// or using ramda, see https://ramdajs.com/docs/#find
import * as R from 'ramda'

R.find(x => x === target, things) // returns target

Resources and Links

JavaScript & TypeScript Libraries

About

Some code examples and explanation of function programming (FP)


Languages

Language:JavaScript 65.7%Language:Elm 34.3%