Skip to content

Instantly share code, notes, and snippets.

@fdietze
Last active October 10, 2017 14:24
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save fdietze/35d72d79abc39cbb3fc83caa4365bb3d to your computer and use it in GitHub Desktop.
Functional Programming Insights

What is a Monad?

A Monad is something that supports flatMap.

Examples: Option, List, Future

flatMap is the same as >>= in Haskell.

What is referential transparency?

An expression is referentially transparent if it can be replaced with its corresponding value without changing the program's behavior.

Example (source):

var x = 1;
x + x

Has the same result as:

1 + 1

And vice versa.

A counter example is:

var x = prompt("Name:");
x + x

Does not have the same result as:

prompt("Name:") + prompt("Name:")

Not referentially transparent:

  • Functions with I/O operations, like console print, file- and networking-operations
  • Factories which produce mutable objects

Advantages:

What is a side-effect?

Every expression which is not referentially transparent has side-effects.

What is a pure function?

A pure function is referentially transparent.

What is an IO-Monad?

An IO-Monad is an anonymous function with side-effects that can be used like a Monad.

How can I program side-effects with only pure functions?

Side-effects are not avoided, but executed as late as possible ("at the end of the World/Universe").

For example: Haskell's main function returns an IO-Monad wich contains all desired side-effects.

Strategy: Compose the side-effects as IO-Monads using pure functions and execute them as late as possible.

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