+ All Categories
Home > Technology > Functional Concepts for OOP Developers

Functional Concepts for OOP Developers

Date post: 14-Aug-2015
Category:
Upload: brweber2
View: 11,595 times
Download: 1 times
Share this document with a friend
107
Functional Programming Bryan Weber Near Infinity Corporation January 2009 λ 1
Transcript
Page 1: Functional Concepts for OOP Developers

FunctionalProgramming

Bryan Weber

Near Infinity Corporation

January 2009λ1

Page 2: Functional Concepts for OOP Developers

About the Speaker

• Let’s be honest

• You don’t know

• You don’t care

• Let’s move on...

2

2

Page 3: Functional Concepts for OOP Developers

Things should not change

and they should

not affect others

3

3

Page 4: Functional Concepts for OOP Developers

and it would be good if they

could do both at the

same time

4

4

Page 5: Functional Concepts for OOP Developers

What’s the point?

5

5

Page 6: Functional Concepts for OOP Developers

What

not how

not when

6

6

Page 7: Functional Concepts for OOP Developers

Before we go any further...

7

7

Page 8: Functional Concepts for OOP Developers

Mathematics!

8

Page 9: Functional Concepts for OOP Developers

Uh oh!

9

Page 10: Functional Concepts for OOP Developers

Please don’t leave...

10

Page 11: Functional Concepts for OOP Developers

Good book

11

Page 12: Functional Concepts for OOP Developers

Functional Languages

Haskell

Clean

F#

ML / OCaml

Lisp / Scheme

Scala

Clojure

XSLT

Erlang

12

12

Page 13: Functional Concepts for OOP Developers

Pure Functional Languages

Haskell

Clean

F#

ML / OCaml

Lisp / Scheme

Scala

Clojure

XSLT

Erlang

13

13

Page 14: Functional Concepts for OOP Developers

Haskell

14

Page 15: Functional Concepts for OOP Developers

Introductory?

15

Page 16: Functional Concepts for OOP Developers

Programming?

16

Page 17: Functional Concepts for OOP Developers

Is it too hard?

17

Page 18: Functional Concepts for OOP Developers

Again?

18

18

Page 19: Functional Concepts for OOP Developers

The foundation

19

Page 20: Functional Concepts for OOP Developers

What is a function?

y = f(x)

20

Page 21: Functional Concepts for OOP Developers

Lambda Calculus

21

Page 22: Functional Concepts for OOP Developers

λ x. x + 2

Lambda expression

22

Page 23: Functional Concepts for OOP Developers

f(x,y) -> z

How do we achieve

functions like...

23

Page 24: Functional Concepts for OOP Developers

Function Currying Example

foo(x,y) -> z bar(x) -> baz

baz(y) -> z24

Page 25: Functional Concepts for OOP Developers

“It's not difficult at all, proc {|x, y, z| x + y + z }.curry

returns the proc object equivalent to proc {|x| proc {|y| proc {|z| x + y + z } } }

See?” matz.

25

Page 26: Functional Concepts for OOP Developers

Why do this in Ruby?

plus_five =proc{|x,y,z|x+y+z }.curry.call(2).call(3)

plus_five[10] #=> 15

26

Page 27: Functional Concepts for OOP Developers

Ruby,

really?

C# too!

LINQ27

Page 28: Functional Concepts for OOP Developers

Arity example (1)

%% sum/1sum(L) -> sum(L,0).

%% sum/2sum([], N) -> N;sum([H|T],N) -> sum(T, H+N).

28

Page 29: Functional Concepts for OOP Developers

Pattern Matchingexample

29

Page 30: Functional Concepts for OOP Developers

-module(patternmatch).

-export([run/0]).

run() ->

tupleassign(),

pmatch(),

invalid().

invalid() ->

Str1 = "have a nice day",

Str2 = "have another nice day",

Str1 = Str2. %% this is an error!

tupleassign() ->

MyTuple = {1,2,3},

{A,B,C} = MyTuple, %% this assigns values to unbound A, B and C

io:format("A:~p B:~p C:~p ~n",[A,B,C]).

pmatch() ->

Str1 = "la la la",

case Str1 of

"foo" ->

io:format("uh oh ~n");

3 ->

io:format("wrong type ~n");

"la la la" ->

io:format("We have a match ~n");

_ ->

io:format("like an else ~n")

end.

30

Page 31: Functional Concepts for OOP Developers

Built in Assertions /

Single Assignment

invalid() -> Str1 = "have a nice day", Str2 = "have another nice day", Str1 = Str2. %% this is an error!

31

Page 32: Functional Concepts for OOP Developers

Multiple Assignment

tupleassign() -> %% create a tuple MyTuple = {1,2,3}, %% assign values to unbound A, B and C {A,B,C} = MyTuple, %% print the result io:format("A:~p B:~p C:~p ~n",[A,B,C]).

32

Page 33: Functional Concepts for OOP Developers

Switch Statement Str1 = "la la la", case Str1 of "foo" -> io:format("uh oh ~n"); 3 -> io:format("wrong type ~n"); "la la la" -> io:format("We have a match ~n"); _ -> io:format("like an else ~n") end.

33

Page 34: Functional Concepts for OOP Developers

Call by Future

34

Page 35: Functional Concepts for OOP Developers

Lazy Evaluation

35

Page 36: Functional Concepts for OOP Developers

Control Structure Example

36

Page 37: Functional Concepts for OOP Developers

DEFINE:

newOr a b = if a then a else b

EXAMPLE:

newOr (4==4) (length [1..] > 0)

37

Page 38: Functional Concepts for OOP Developers

And now, for our

featured

presentation

38

Page 39: Functional Concepts for OOP Developers

Immutability

Concurrency

Side Effects

39

Page 40: Functional Concepts for OOP Developers

Functional

Object Oriented

40

Page 41: Functional Concepts for OOP Developers

Immutability

Concurrency

Side Effects

41

Page 42: Functional Concepts for OOP Developers

Object Oriented

Functional

42

Page 43: Functional Concepts for OOP Developers

Enlightenment?

43

Page 44: Functional Concepts for OOP Developers

Immutability

Concurrency

Side Effects

44

Page 45: Functional Concepts for OOP Developers

Immutability

Concurrency

Side Effects

45

Page 46: Functional Concepts for OOP Developers

Can Things Change?

46

Page 47: Functional Concepts for OOP Developers

Immutable Collectionsexample

Lists (IPersistentList)

Vectors (IPersistentVector)

Maps (IPersistentMap)

StructMaps

ArrayMaps*

Sets

47

Page 48: Functional Concepts for OOP Developers

PROGRAM: (2)

(in-ns 'main)(clojure/refer 'clojure)

(defn main [args] (def x (list 1 2 3)) (def y (conj x "hello" "there" "world")) (println "list is: [" (apply str (interpose ", " y)) "]") )

PRODUCES:

list is: [ world, there, hello, 1, 2, 3 ]

48

Page 49: Functional Concepts for OOP Developers

Erlang Lists (3)

append(List1, List2) -> List3

Types:

List1 = List2 = List3 = [term()]

Returns a new list List3 which is made from the elements of List1 followed by the elements of List2.

49

Page 50: Functional Concepts for OOP Developers

Immutability

Concurrency

Side Effects

50

Page 51: Functional Concepts for OOP Developers

Complexity

51

Page 52: Functional Concepts for OOP Developers

No shared state

52

Page 53: Functional Concepts for OOP Developers

STMExample

53

Page 54: Functional Concepts for OOP Developers

Operation Type Signature

atomically STM a -> IO a

retry STM a

orElse STM a -> STM a -> STM a

newTVar a -> STM (TVar a)

readTVar TVar a -> STM a

writeTVar TVar a -> a -> STM ()

54

Page 55: Functional Concepts for OOP Developers

module Main where<< ... imports omitted ... >>main = do shared <- atomically $ newTVar 0 before <- atomRead shared putStrLn $ "Before: " ++ show before forkIO $ 25 `timesDo` (dispVar shared >> milliSleep 20) forkIO $ 10 `timesDo` (appV ((+) 2) shared >> milliSleep 50) forkIO $ 20 `timesDo` (appV pred shared >> milliSleep 25) milliSleep 800 after <- atomRead shared putStrLn $ "After: " ++ show after where timesDo = replicateM_ milliSleep = threadDelay . (*) 1000atomRead = atomically . readTVardispVar x = atomRead x >>= printappV fn x = atomically $ readTVar x >>= writeTVar x . fn

(4)

55

Page 56: Functional Concepts for OOP Developers

Message Passing

56

Page 57: Functional Concepts for OOP Developers

Actor Primitives

spawn

send (!)

receive

57

Page 58: Functional Concepts for OOP Developers

actor

Actor

58

Page 59: Functional Concepts for OOP Developers

Spawn

Actor Actor

59

Page 60: Functional Concepts for OOP Developers

Send

Actor Actor

60

Page 61: Functional Concepts for OOP Developers

Receive (pull model)

Actor Actor

61

Page 62: Functional Concepts for OOP Developers

Actor Example

62

Page 63: Functional Concepts for OOP Developers

-module(actor).-export([run/0]).

act() -> receive Message -> io:format("You said: ~p~n",[Message]) end.

run() -> Pid = spawn(fun act/0), Pid ! "Foobarbaz".

63

Page 64: Functional Concepts for OOP Developers

Immutability

Concurrency

Side Effects

64

Page 65: Functional Concepts for OOP Developers

Purity

65

65

Page 66: Functional Concepts for OOP Developers

Side effects

66

66

Page 67: Functional Concepts for OOP Developers

Your program

You

Your

CodeAPI

Black Box

67

67

Page 68: Functional Concepts for OOP Developers

Your program

You

Your

CodeAPI

Black Box

StateState

68

68

Page 69: Functional Concepts for OOP Developers

Your program

You

Your

CodeAPI

Black Box

State

(Memory)Database

Network

File System

69

69

Page 70: Functional Concepts for OOP Developers

Launch Missiles

70

70

Page 71: Functional Concepts for OOP Developers

IO

Network

Database

File System

Console

ALSO

Exceptions

Randomness

Memory

Order

71

Page 72: Functional Concepts for OOP Developers

Side effects are bad, mkay?

72

Page 73: Functional Concepts for OOP Developers

What can I do then?

73

Page 74: Functional Concepts for OOP Developers

Monads!

74

Page 75: Functional Concepts for OOP Developers

What is a Monad?

75

Page 76: Functional Concepts for OOP Developers

Monadic Laws

1) Left identify

2) Right identity

3) Associativity

76

Page 77: Functional Concepts for OOP Developers

Monad

example

77

Page 78: Functional Concepts for OOP Developers

hPutStr :: Handle -> String -> IO ()hGetLine :: Handle -> IO String

hEchoLine :: Handle -> IO StringhEchoLine h = do { s <- hGetLine h ; hPutStr h (“I read: ” ++ s ++ “\n”) ; return s}

(5)

78

Page 79: Functional Concepts for OOP Developers

Does order matter?

79

Page 80: Functional Concepts for OOP Developers

Order is a side effect as well..

80

Page 81: Functional Concepts for OOP Developers

Order

example

81

Page 82: Functional Concepts for OOP Developers

func(x,y,z) -> r

x ba ry z

82

Page 83: Functional Concepts for OOP Developers

func(x,y,z) -> r

x ba ry z

83

Page 84: Functional Concepts for OOP Developers

Data dependency

example

84

Page 85: Functional Concepts for OOP Developers

func(x,y) -> z

x ba zy,a b

85

Page 86: Functional Concepts for OOP Developers

func(x,y) -> z

x ba zy,a b

86

Page 87: Functional Concepts for OOP Developers

func(x,y) -> z

x ba zy,a b

87

Page 88: Functional Concepts for OOP Developers

func(x,y) -> z

x ba zy,a b

88

Page 89: Functional Concepts for OOP Developers

Function

OptimizationExample

f = g(x) + g(x)

89

Page 90: Functional Concepts for OOP Developers

The Real WOrld

90

Page 91: Functional Concepts for OOP Developers

No time for:Polymorphism

Lists

Tuples

Guards

Accumulators

Continuations

Comprehensions

Fault Tolerance

Type Systems

Process Linking

Recursion (TCO)

Higher Order Functions

91

Page 92: Functional Concepts for OOP Developers

Summary

92

Page 93: Functional Concepts for OOP Developers

Functions (Math)

93

Page 94: Functional Concepts for OOP Developers

Functions (Math)

Immutability

94

Page 95: Functional Concepts for OOP Developers

Functions (Math)

Immutability

Concurrency

95

Page 96: Functional Concepts for OOP Developers

Functions (Math)

Immutability

Concurrency

Developer

Optimizations

96

Page 97: Functional Concepts for OOP Developers

Functions (Math)

Immutability Side Effects

Concurrency

Developer

Optimizations

97

Page 98: Functional Concepts for OOP Developers

Functions (Math)

Immutability Side Effects

Concurrency

Developer

Optimizations

Monads

98

Page 99: Functional Concepts for OOP Developers

Functions (Math)

Immutability Side Effects

Concurrency Monads

Developer

Optimizations

Automated

Optimizations

99

Page 100: Functional Concepts for OOP Developers

Things should not change

(but state is great!) and they should

not affect others

(without notifying us)100

100

Page 101: Functional Concepts for OOP Developers

and it would be good if they

could do both at the

same time

(all the time)

101

101

Page 102: Functional Concepts for OOP Developers

Resources

102

Page 103: Functional Concepts for OOP Developers

BooksBeautiful Code (Oram and Wilson)

Real World Haskell (O’Sullivan, Stewart and Goerzen)

Programming Erlang (Armstrong)

Foundations of F# (Pickering)

Expert F# (Syme, Granicz and Cisternino)

F# for Scientists (Harrop)

Programming in Haskell (Hutton)

Coming Soon

Programming Scala (Subramaniam)

Programming Clojure (Halloway)

103

Page 105: Functional Concepts for OOP Developers

IRC

chat.freenode.net

#haskell

#scala

#erlang

#clojure

#fsharp

105

Page 106: Functional Concepts for OOP Developers

References

1) Example shamelessly stolen from page 42 of “Programming Erlang” by Joe Armstrong.2) Shamelessly stolen from Clojure doc3) From Erlang stdlib documentation4) Shamelessly stolen from http://www.haskell.org/haskellwiki/Simple_STM_example5) Example from “Beautiful Code” by Oram and Wilson

106

Page 107: Functional Concepts for OOP Developers

Questions?

107


Recommended