Functional Programming – What we will be learning – Survey



Functional Programming – What we will be learning – Survey

0 0


FunctionalProgramming

Research and presentation on functional programming.

On Github mhhussain / FunctionalProgramming

Functional Programming

by yours truly

What we will be learning

What it is How it works Why it's important

Why am I presenting this

  • Because I find it interesting

Ground rules

  • Pay attention
  • No questions
  • Tell me slow down

Survey

Prompt: Without looking it up, explain what you think functional programming is.

Best answer: In computer science, functional programming is a programming paradigm — a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. Just kidding... I thought it was something similar to procedural programming.

Breakdown

  • 4. Programming paradigm
  • 1. Evaluation of functions
  • 3. Avoids changing state
  • 2. Avoids mutable data

Breakdown

Evaluation of functions Avoids mutable data Avoids changing state Programming paradigm

Brief history lesson

  • 1932 - Alonzo Church and Stephen C. Kleene
  • Lambda calculus

much history

Church and Kleene were studying the foundation of mathematics and wanted to get to its very roots. They wanted to abstract it out as far as they possibly could.

They abstracted mathematics down to what they believed was its most basic and fundamental construct, the function. They created a new notion for their math using the greek letter lambda (λ)

Functions

  • f(x) = x + 10 --> (λx.x + 10)
    • This denotes a function that takes one parameter, x, and adds 10 to it
    • (λx.x + 10) 32 = 32 + 10 = 42 -- giving an argument is called an application

Functions

  • (λop.λx.(op x x)) (+) 21 = + 21 21 = 42
  • (λop.λx.(op x x)) (*) 21 = * 21 21 = 441

Such past

Back in the 30s, it didn't exactly catch on because it didn't fulfill its original purpose, but once computers took over, it served as the theoretical basis and inspiration for functional programming. Wow.

Questions?

Back to before

Evaluation of functions Avoids mutable data Avoids changing state Programming paradigm

What is functional programming

  • Not the opposite of oop, it's more the opposite of imperative programming
  • Functional programming is like explaining to a mathmetician how to solve a problem; imperative programming is telling an idiot what to do
  • Functional programming is a style of programming that emphasizes the evaluation of expressions, rather than the executions of commands. The expressions in these languages are formed by using functions to combine basic values

Execution of commands

  • The program is expressed as a sequence of commands. Commands specify how to achieve the end result by creating objects and manipulating them
    • This is where the tie in to oop comes from
    • OOP is very typically imperative, but not naturally
  • The approach uses objects that can be changed and the code describes how to change those objects

Execution of commands

Example: We're making a cup of coffee. The cup of coffee is our object. We add cream and sugar to it, and thereby change the object.

							
class CupOfCoffee {
  int cream;
  int sugar
};
var yay = new CupOfCoffee();
yay.cream++;
yay.sugar++;
							
						

Evaluation of expressions

  • The program code is an expression that specifies properties of the object we want to get as the result
  • We don't specify the steps necessary to construct the object and we can't accidentally use the object before it's created

Evaluation of expressions

Example: Same coffee example, let's say you want to add cream and sugar to it

							
var yay = new CupOfCoffee();
var nowWithSugar = yay.AddSugar(1);
var nowWithCreamAndSugar = nowWithSugar.AddCream(1);
							
						
Execution of commands
							
class CupOfCoffee {
  int cream;
  int sugar
};
var yay = new CupOfCoffee();
yay.cream++;
yay.sugar++;
							
						
Evaluation of expressions
							
var yay = new CupOfCoffee();
var nowWithSugar = yay.AddSugar(1);
var nowWithCreamAndSugar = nowWithSugar.AddCream(1);
							
						

Questions?

Back to before

evaluation of functions avoids mutable data avoids changing state programming paradigm

Declarative vs imperative

Imperative programming

Imperative programming is the execution of commands. The program consists of statements that specify how to change the state of the program. It is a step-by-step description of telling the computer how to accomplist it's overall task.

Declarative programming

In declarative programming style, we express the logic of the program without specifying the execution details.

This is where the difficulty lies. You can turn it over in your head as much as you want, but it won't make sense. This is where you would need to start unravel the theory of computer science that you have learned. We are mostly taught that the logic of a program is tightly wound to the programs execution.

Example

You have a list of customer and you want to pluck from that list all of the customers who's age is greater than 65.

Imperatively

Initialize a loop, iterate through every customer, and if the age is greater than 65, then add that customer to some temp list. Once the loop terminates, return the temp list.

							
for (var i = 0; i < customers.Count(); i++)
{
  if (customers[i].age > 65)
  {
    tempList.Add(customers[i]);
  }
}
return tempList;
							
						

Declaratively

Filter from customers where customer age is greater than 65.

SQL

							
SELECT * FROM Customer WHERE Age > 65
							
						

C# (LINQ)

							
return (from c in customers
where c.age > 65
select c)
							
						

C# (LINQ Extensions)

							
return customers.Where(c => c.age > 65);
							
						

Javascript (underscore or lodash)

							
return _.filter(customers, function (c) {
  return c.age > 65
});
							
						

C++ (11 - lambdas are super clunky and awful)

							
filter(customers.begin(), customers.end(),
  [] (Customer c) {
    return c.age > 65;
  }
);
							
						

Java

							
return customers.stream()
  .filter(c -> c.age > 65)
  .collect(Collectors.toList());
							
						

Python (Lambda)

							
filter(lambda c: c.age > 65, customers)
							
						

Python (List comprehension)

							
[c for customer in customers if customer.age > 65]
							
						

F#

							
customers |> List.filter (fun (c) -> c.age > 65)
							
						

F#

							
let over65(c) = c.age > 65
customers |> List.filter over65
							
						
Imperative - execution of commands
							
for (var i = 0; i < customers.Count(); i++)
{
  if (customers[i].age > 65)
  {
    tempList.Add(customers[i]);
  }
}
return tempList;
							
						
Declarative - evaluation of expressions
							
customers |> List.filter (fun (c) -> c.age > 65)
							
						

Questions?

Im/Mutability

  • This is why it's hard
  • Coffee example
  • Immutable - once the value is set, it cannot be changed
  • Strict vs non-strict
  • Variable vs value

Why Immutability

  • Much easier to predict what a program will do
  • Stateless-ness
  • None, or less, side effects
  • Function output is extremely predictable - functions are dependent purely on input

Example: Sum up all number between two numbers (i.e. SumNumbers(5, 10) -> 45)

							
int SumNumbers(int from, int to)
{
  int retVal = 0;
  for (var i = from; i <= to; i++)
  {
    retVal += i;
  }
  return retVal;
}
							
						

Example: Sum up all number between two numbers (i.e. SumNumbers(5, 10) -> 45)

							
int SumNumbers(int from, int to)
{
  return
    (from > to)
      ? 0
      : { var sumRest = SumNumbers(from + 1, to);
          from + sumRest; };
}
							
						

Memory issues

							
$scope.createEmployee = function() {
  $scope.loading++;

  var newEmployee = {
    Person_Sk: $scope.employee.Person_Sk,
    UserName: $scope.employee.UserName,
    FirstName: $scope.employee.FirstName,
    MiddleName: $scope.employee.MiddleName,
    LastName: $scope.employee.LastName,
    IsAdmin: $scope.employee.IsAdmin,
    IsActive: $scope.employee.IsActive,
    HireDate: moment($scope.employee.HireDate).format("YYYY-MM-DD"),
    EmployeeTypeLookup_Sk: $scope.employeeType.LookupElement_Sk,
    YearsProfessionalPrior: $scope.employee.YearsProfessionalPrior
  };

  employeeRepository.Post(newEmployee)
    .done(function() {
      $scope.loading--;
      $scope.goToEmployees();
  });
};
 							
						

Tail recursion

							
int Factorial(int n, int total = 1)
{
  if (n == 0) return total;
  return Factorial(n - 1, n * total);
}
							
						

Questions?

State

  • STUDENT: Sir, can I ask a question?
  • TEACHER: Yes!
  • STUDENT: How do you put an elephant inside a fridge?
  • TEACHER: I don't know.
  • STUDENT: It's easy, you just open the fridge and put it in. I have another question!
  • TEACHER: Ok, ask.
  • STUDENT: How to put a donkey inside the fridge?
  • TEACHER: It's easy, you just open the fridge and put it in.
  • STUDENT: No sir, You just open the fridge take out the elephant and put it in.
  • TEACHER: Ooh...ok!!
  • STUDENT: Let me ask another one. If all the animals went to the lion's birthday party, and one animal went missing which one would it be?
  • TEACHER: The lion of course! Because it would eat all the animals.
  • STUDENT: No sir, it is the donkey, because it's still inside the fridge.
  • TEACHER: Are you kidding me?
  • STUDENT: No sir, one last question.
  • TEACHER: Ok!
  • STUDENT: If there's a river known to be full of crocodiles and you wanted to cross, how would you?
  • TEACHER: There's no way, I would need a boat to cross.
  • STUDENT: No sir, you just swim and cross it because all the animals went to the lion's birthday party.

Finale

  • Programming is hard
  • Functional programming is hard
  • It is a paradigm, not simply a style (like declarative) or a framework/library
  • It's important to know about and it has gained a lot of traction in the last decade or so
  • .NET: F#, Nemerle
  • JVM: Scala, Clojure
  • Erlang: Erlang, elixir
  • Native: Haskell, OCaml

Final note: Functional programming is a different way of thinking. Where most programming langauges and paradigms sprouted from mathematice, functional is and always will be very, very deeply rooted in it.

Questions?

Functional Programming by yours truly