Functional

By Jeetaditya Chatterjee

🎵 Its time to get functional 🎵

Press s for speaker notes

What is functional programming

functional programming is a paradigm where the entire system is modeled as a function of its inputs and outputs

.. what does this mean?

What that means

when you call a function you give it a set of inputs and it returns an output.

def function(input):
    output = input + 1
    return output

this is in essence how the entire program is modeled

I just wanna code bro

This means a couple things.

  • Programs are stateless
  • All functions have to be pure (No side effects)
  • functions are first class
  • some more we will get too

Statelessness

  class User
    def initialize(first_name, age)
      @first_name = first_name
      @age = age
    end

    # Create reader methods to get the age
    attr_reader :age

    def make_older(number_of_years)
      @age += number_of_years
    end
  end

  user = User.new("Bernhard", 31)
  # => #<User:0x007fd2cb0e6cf8 @first_name="Bernhard", @age=31>

  user.age
  # => 31

  user.make_older(5)
  # => 36

  user.age
  # => 36
defmodule User do
  defstruct first_name: nil,
            age: nil

  def age(user)
    user.age
  end

  def make_older(user, number_of_years)
    Map.put(user, :age, number_of_years)
  end
end

user = %User{first_name: "Bernhard", age: 31}
# => %User{first_name: "Bernhard", age: 31}

user.age
# => 31

make_older(user, 5)
# => %User{first_name: "Bernhard", age: 36}

user.age(user)
# => 31

Function purity

x = 10


def add(num):
    x = x + 1

print(x)
# => 11
x = 10


def add(num1, num2):
    return num1 + num2


y = add(x, 1)

first class functions

var x = 10 + x

function x =  if x > 10 do stuff.. -- probably no valid
someReallyLongFunctionName = ...

name = someReallyLongFunctionName

Higher order functions

output = (input).map do |s|
  s.sub("\n", "").sub(/,/, "").gsub(/;.+/, "").strip.split
end

function composition

  • f(x) = x + 2
  • g(x) = x - 8
  • f(g(x)) = (x - 8) + 2

 f x = x + 2
 g x = x - 8

 (f.g) 10 -- composition
 -- => 4

What have I missed

  • types and type classes Haskell is a static language so you have to define types. but this also means you have to give functions types..

      function :: Integer -> Integer -> Integer
    
      function x y = x + y
    
  • partial function application

      add :: Integer -> Integer -> Integer
      addSix :: Integer -> Integer
      addSix = add 6
      x = addSix 3
      -- x = 9
    
  • other higher order funtuons
    • filter (filter an array acording to some check)

      filter (>6)[2,5,6,8,9]
      -- => [8,9]
            
      
      
    • fold / reduce (use recursion to reduce a list) you can do it from the left or the right

      foldl (+) 0 [2, 3, 4, 5]
        -- => basically sum down an array from the left most side
      
  • lists this is an entire chapter. and i am tired

I am done now