Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flamelier/ca1674e2585e950f4b078acc13f2c0e2 to your computer and use it in GitHub Desktop.
Save flamelier/ca1674e2585e950f4b078acc13f2c0e2 to your computer and use it in GitHub Desktop.
Functional programming guide. Keywords: function functional program curry currying monad monadic immutable immutability

FUNCTIONAL PROGRAMMING GUIDE

IMPORTANT NOTES TO THE ZEALOTS: Listen to me you functional programming zealot. Writting opaque functions is ok! Chill the F out. This programming style is just another useful skill that elegantly solves certain types of problems. This is NOT the Thor hammer that will crush all your nails you geek. So relaaaax maaaann.

Table of contents

Key concepts

Function as first-class citizen

Pure function and referential transparency

Those two concepts are linked together. A pure function is a function that returns the same output each time the same input is providedm and it must do so with side effects. This means that evaluation of a pure function for a specificic set of inputs can be replaced with its output. The last sentence can be rewritten as follow: A pure function is referentially transparent. The opposite is referential opacity. Let see this with an example:

let counter = 0

const pureIncrementFn = i => i+1

const opaqueIncrementFn = i => {
	counter++
	return i+counter
}

console.log(pureIncrementFn(1)) // 2
console.log(pureIncrementFn(1)) // 2

console.log(opaqueIncrementFn(1)) // 2
console.log(opaqueIncrementFn(1)) // 3
console.log(opaqueIncrementFn(1)) // 4

The above example shows that opaqueIncrementFn is undeterministic because each time it is evaluated, it mutates the counter variable. It is not possible to know for sure what the output will be, there, the following two statements are not equivalent:

opaqueIncrementFn(1) == 2
// and
2 == 2

It is not possible to replace opaqueIncrementFn(1) with its value. That's why opaqueIncrementFn is not referentially transparent. Whereas pureIncrementFn is:

pureIncrementFn(1) == 2
// is equivalent to
2 == 2

Function composition

Basic composition

Currying

Immutability

Monad

https://dzone.com/articles/simplifying-monads-in-scala#:~:text=Monads%20are%20not%20at%20all,wraps%20another%20object%20in%20Scala.

Functional error handling

Annex

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment