Calculus, Not Rocket Science – Or, What FP Can Give You in an OO World – Is it...



Calculus, Not Rocket Science – Or, What FP Can Give You in an OO World – Is it...

0 0


calculus-not-rocket-science

A May 2013 Lab49 DC Tech Breakfast presentation

On Github wsh / calculus-not-rocket-science

Calculus, Not Rocket Science

Or, What FP Can Give You in an OO World

Will Hayworth / @_wsh

Lab49

May 17, 2013

What's FP?

What are functions?

  • Computation is function application
  • Functions are free variables with operations
  • Application (or partial application) entails resolving those variables

What are objects?

  • Smalltalk: pure state (fields + messages)
  • Java/C++: state + functions
  • Ruby: kind of both?

What's FP?

Is it...

  • First-class functions?
  • Not having side effects?
  • (Referential transparency?)

What is a “functional language”? If it’s a language with first-class functions, then C is a functional language. If it’s a language that disallows hidden side-effects, then Haskell isn’t a functional language.

— our own Kalani Thielen

FP as a Modality

not a family

Transformations

Not iterations

Constrained state

Local over global

How does this work?

foo = [1,2,3,4,5]
for i in (0...foo.size)
    foo[i] = foo[i] * 2
end

foo
# => [2,4,6,8,10]
foo = [1,2,3,4,5]
bar = []
for element in foo
    bar << element * 2
end

foo
# => [1,2,3,4,5]

bar
# => [2,4,6,8,10]
foo = [1,2,3,4,5]
foo.map {|x| x * 2}
# => [2,4,6,8,10]

Why do this?

foo = [1,2,3,4,5]
foo.map {|x| x * 2}
foo = some_dataset
foo.map {|x| costly_operation(x)}.reduce {|m, o| aggregation(m, o)}

I get it but...

We work in Java

Mixed bag from an FP standpoint

  • Constrained state: encapsulation
  • First-class functions: anonymous inner classes
element.addListener(new NotARealClosure() {
    public void someCallback(Event e)
    {
        // ugh.
    }
});
These [functional idioms] are by far the most easily (and most commonly) abused parts of Guava, and when you go to preposterous lengths to make your code "a one-liner," the Guava team weeps.

For all Java's flaws

FP can make ours better

Exhibit A:

Option

Functional languages

love Option

scala> val x = List((1,2)).toMap
x: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2)
scala> x.get(1)
res2: Option[Int] = Some(2)
scala> x.get(3)
res3: Option[Int] = None
scala> x.getOrElse(4, 5)
res4: Option[Int] = 5

What does null mean?

HashMap<Integer, Integer> someHashMap = new HashMap<>();
someHashMap.put(1, 2);
Optional<Integer> foo = Optional.fromNullable(someHashMap.get(1));
Optional<Integer> bar = Optional.fromNullable(someHashMap.get(3));

if (foo.isPresent()) foo.get(); // 2
bar.isPresent(); // false
bar.get(); // IllegalStateException
bar.or(5); // 5

Why is this handy?

  • No NullPointerExceptions. Ever.
  • You're required to handle every case.

Exhibit B:

Immutable________

Functional languages

love Immutability

Thanks!