Behrooz Shabani

@everplays

  • RadioTray - Python
  • Archipel - Python / Objective-J
  • ShadowSocks - Python
  • MiniProfiler - Ruby
  • Diaspora - Ruby
  • Peace - Scala
  • MapKit - Java / Objective-C
  • ChildBrowser - Java / Objective-C
  • Status.net / GNUSocial - php
  • ...

Programming

  • imperative
  • declarative
    • functional
    • logic

OOP

The big idea is "messaging".
^ Alan Kay

Pure OO?

  • classes
  • Imperative types
    by using Peano numbers you can implement imperative types as objects
  • methods
  • Operations

Isolation

system.exit()

Functional programming

  • immutability
  • higher order functions

Math

y = 10
x = y + 9
y = 11 // you can't do it in math!

brain/logic & mutability

No man ever steps in the same river twice.
^ Heraclitus
read more: "Process and reality" by Alfred North Whitehead

time is atomic

2.418884326505(16)×10^17 s

              |------|
Book -------- |-Val1-|
    \         |------|
     \
      \
       \  |------|
        \ |-Val2-|
          |------|

Why immutability could be a good thing?

concurrency

Garbage collection / Memory management

      r           r
     / \           \
    o   x   ---->   x
   / \ / \           \
  o  o o              n

   we can use the left
        side as is
don't copy, use old data, they won't change

All functional languages are side-effect free? no.
Erlang, scala, clojure, F#, ...

higher order functions

// data
var x = 10;

// code
function foo() { ... }

code is data, too.

remember the "turing machine"?

// so, let's pass them around like other values

var list = [5, 10, 1];

list.sort(function(a, b){
    return a - b;
}); // [1, 5, 10]

pure functions

always return the same result where called with the same arguments.

(defn plusOne [a] (+ a 1))

(plusOne 2) #_ always returns 3, no matter what!

every language with HOF is functional? no.
js, ruby, smalltalk, (even!) java

so functional programming is not just:
  • immutability
  • higher order functions

let's get a bit more into depth

performance of mutable vs immutable

adding one million items to a Vector:

scala

immutable: ~127ms
  mutable: ~89ms

Clojure

immutable: ~114ms
  mutable: ~74ms

This is crazy, C should go faster, well yes it does but it had a lock. Erlang was slower but lock-free and thus scaleable. So removing the C and doing image processing in Erlang was faster than doing it in C.
^ Joe Armstrong

read more:
functional programming patterns in scala and clojure
&
http://joearms.github.io/2013/03/28/solving-the-wrong-problem.html

loops

there's no mutable state, so there's no for / while / foreach / ...

recursive functions

factorial(0) -> 1;
factorial(N) -> N * factorial(N-1).

stack overflow

01: 20 * factorial(19)
02:     19 * factorial(18)
03:          18 * factorial(17)
               ...
                  ...
                     ...
19:                         2 * factorial(1)
20:                             1 * factorial(0)

tail recursion

factorial(N) -> tail_fac(N, 1).

tail_fac(0,Acc) -> Acc;
tail_fac(N,Acc) -> tail_fac(N-1, N*Acc).
01: 20, 1
01: 19, 20
01: 18, 380
...
01: 0, 2432902008176640000

you need to be careful, you might lose your stack trace!
(not in erlang)

Monads

  • Box of pandora
  • Space suits
  • Nuclear waste container

monoid

x: A
f: A -> A
g: A -> A

f(g(x)) = f.g(x) = h(x)

h: A -> A

^ group theory

monoid rules

  1. f(g.h) = (f.g).h
  2. zero unit

now if argument types differ, we're in category theory but we already know that in order to call a function, argument type has to match.

what these monads are useful for?

collections of any kind: in-memory, streams (IO), databases

unix' pipe, does the thing that monads do:
cat ~/foo.txt | sed 's/bar baz/qux/g' | grep 'qux' | wc -l
scala:
  Option (is a monad)
  /    \
None  Some
// row will be a Map (assoc array in php)
val row = SQLSelectOneRow("select title from posts where id = 10")

// check if we could find the row
if ( row ) {
    return row.get("title")
} else {
    return None
}
// let's assume row is wrapped in Option
val row = SQLSelectOneRow("select title from posts where id = 10")

row map ( _.get("title") )

pattern matching

case class Person(val firstName:String, val lastName:String, val age:Int)

val behrooz = Person("Behrooz", "Shabani", 24)
val martin = Person("Martin", "Odersky", 55)

def fullNameOfPersonIfUnder30(p:Person) = p match {
    case Person(fName, lName, age) if age < 30 => Some(fName + " " + lName)
    case _ => None
}
fullNameOfPersonIfUnder30(behrooz)
// Option[String] = Some(Behrooz Shabani)

fullNameOfPersonIfUnder30(martin)
// Option[String] = None

read more:
pattern matching is an awesome solution for "expression problem"
&
Beginning Scala by David Pollak (Chapter 8)

actors

are not really connected to FP but as languages we talked about have actors*, I'll talk about them too.
* agents in case of clojure are not exactly actor

run() ->
    spawn(counter, counter, [0]).

counter(Sum) ->
    receive
        print ->
            io:fwrite("Value is ~w~n", [Sum]),
            counter(Sum);
        {value, Sender} ->
            Sender ! Sum,
            counter(Sum);
        {inc, Amount} ->
            counter(Sum+Amount);
        stop ->
            io:fwrite("Stopping ...")
    end.
CounterActor = counter:run().

% prints: Value is 0
CounterActor ! print.

% increase it by 3
CounterActor ! {inc, 3}.

% prints: Value is 3
CounterActor ! print.
CounterActor ! {value, self()}.
receive
    TheReceivedValue ->
        io:frwite("double of Value is ~w~n", [TheReceivedValue*2])
end.
who/what is using ...

Scala

  • Novell
  • twitter
  • LinkedIn
  • Play

Erlang

  • Amazon
  • Ericsson
  • Facebook
  • RabbitMQ

Clojure

  • Prismatic
  • ReadyForZero
  • Montoux
  • Ring

resources:

http://en.wikipedia.org/wiki/Smalltalk
http://joearms.github.io/ by Joe Armstrong
http://pragprog.com/book/mbfpp/functional-programming-patterns-in-scala-and-clojure by Michael Bevilacqua-Linn
http://www.infoq.com/presentations/Are-We-There-Yet-Rich-Hickey by Rick Hickey
http://www.infoq.com/presentations/functional-pros-cons by Gilad Bracha
http://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads by Brian Beckman
Coursera Scala by Martin Odersky

http://twitter.com/everplays
^ twitter (@everplays)


Questions?

LGBT flag
R.I.P. Alan Turing.