Sorter coder

The last functional programming page

July 04, 2019,tags : regex, level: shu, easy
<This is a draft, it is work in progress>

The history [skip if its complex or boring, not mandatory]

Alan turing invented the Turing machine [read 1 and 0's and output 1 or 0 depending on current state of Turing machine] which capture a "state based" model of computation, his Phd advisor Alonzo Church invented lambda calculus to express functional model of computation. Lambda calculus : Alonzo Church working on foundation of mathematics

  • Any turing machine program can be translated to a Lambda Calculus program
  • Using pure functions without internal state
  • Compiled down a very small core language which is essentially a glorified form of lambda calculus.
  • Ycombinator

link

The core ideas

memory waste ?
creating new datastructures
on every change ?
Functional programming
Use pure functions
Dont iterate
use map() reduce() filter()
Use immutable
data structures
lazy
evaluation
No side effects
First class functions
Higher Order functions
Persistent Data Structures
efficient copy-on-write

What about state then ?

If functions are not allowed side effects how to interact with the real world where objects are stateful.
e.g. If you are writing to a database in a function, it is stateful, if it is executed multiple times if affect can be different and depend on database state.

Pure functions

A pure function has no side effects.

No side effects

A pure function returns the same output for the same input values no matter how many times it is called, or when (time) it is called, just like a mathematical function without affecting something else, or no side effects.

What are some examples of side effects ?
  • Writing to the database
  • Changing the global state
  • Printing to the console
  • Changing (mutating) a mutable object:
    If you change a mutable list in a function its not pure ! because it is a side effect and multiple function calls can have different results

So essentially your functions are just data transformers nothing else. But why the trouble, what is it good for ? Pure functions and immutable data allows us to solve the major problems when dealing with parallel execution of same function in multiple threads. We do not need careful synchronisation, locks all of that is gone. Pure functions can be executed in parallel without any worry.

Then how do you get any real life work done like input from user or write to db, logging ? Yes thats a problem read on, we will explain it.

Is there

First class functions
Higher order function
Persistent data structures
buzz words
Monads
Reification
Currying