Upload
brweber2
View
11.602
Download
1
Embed Size (px)
Citation preview
FunctionalProgramming
Bryan Weber
Near Infinity Corporation
January 2009λ1
About the Speaker
• Let’s be honest
• You don’t know
• You don’t care
• Let’s move on...
2
2
Things should not change
and they should
not affect others
3
3
and it would be good if they
could do both at the
same time
4
4
What’s the point?
5
5
What
not how
not when
6
6
Before we go any further...
7
7
Mathematics!
8
Uh oh!
9
Please don’t leave...
10
Good book
11
Functional Languages
Haskell
Clean
F#
ML / OCaml
Lisp / Scheme
Scala
Clojure
XSLT
Erlang
12
12
Pure Functional Languages
Haskell
Clean
F#
ML / OCaml
Lisp / Scheme
Scala
Clojure
XSLT
Erlang
13
13
Haskell
14
Introductory?
15
Programming?
16
Is it too hard?
17
Again?
18
18
The foundation
19
What is a function?
y = f(x)
20
Lambda Calculus
21
λ x. x + 2
Lambda expression
22
f(x,y) -> z
How do we achieve
functions like...
23
Function Currying Example
foo(x,y) -> z bar(x) -> baz
baz(y) -> z24
“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
Why do this in Ruby?
plus_five =proc{|x,y,z|x+y+z }.curry.call(2).call(3)
plus_five[10] #=> 15
26
Ruby,
really?
C# too!
LINQ27
Arity example (1)
%% sum/1sum(L) -> sum(L,0).
%% sum/2sum([], N) -> N;sum([H|T],N) -> sum(T, H+N).
28
Pattern Matchingexample
29
-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
Built in Assertions /
Single Assignment
invalid() -> Str1 = "have a nice day", Str2 = "have another nice day", Str1 = Str2. %% this is an error!
31
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
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
Call by Future
34
Lazy Evaluation
35
Control Structure Example
36
DEFINE:
newOr a b = if a then a else b
EXAMPLE:
newOr (4==4) (length [1..] > 0)
37
And now, for our
featured
presentation
38
Immutability
Concurrency
Side Effects
39
Functional
Object Oriented
40
Immutability
Concurrency
Side Effects
41
Object Oriented
Functional
42
Enlightenment?
43
Immutability
Concurrency
Side Effects
44
Immutability
Concurrency
Side Effects
45
Can Things Change?
46
Immutable Collectionsexample
Lists (IPersistentList)
Vectors (IPersistentVector)
Maps (IPersistentMap)
StructMaps
ArrayMaps*
Sets
47
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
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
Immutability
Concurrency
Side Effects
50
Complexity
51
No shared state
52
STMExample
53
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
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
Message Passing
56
Actor Primitives
spawn
send (!)
receive
57
actor
Actor
58
Spawn
Actor Actor
59
Send
Actor Actor
60
Receive (pull model)
Actor Actor
61
Actor Example
62
-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
Immutability
Concurrency
Side Effects
64
Purity
65
65
Side effects
66
66
Your program
You
Your
CodeAPI
Black Box
67
67
Your program
You
Your
CodeAPI
Black Box
StateState
68
68
Your program
You
Your
CodeAPI
Black Box
State
(Memory)Database
Network
File System
69
69
Launch Missiles
70
70
IO
Network
Database
File System
Console
ALSO
Exceptions
Randomness
Memory
Order
71
Side effects are bad, mkay?
72
What can I do then?
73
Monads!
74
What is a Monad?
75
Monadic Laws
1) Left identify
2) Right identity
3) Associativity
76
Monad
example
77
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
Does order matter?
79
Order is a side effect as well..
80
Order
example
81
func(x,y,z) -> r
x ba ry z
82
func(x,y,z) -> r
x ba ry z
83
Data dependency
example
84
func(x,y) -> z
x ba zy,a b
85
func(x,y) -> z
x ba zy,a b
86
func(x,y) -> z
x ba zy,a b
87
func(x,y) -> z
x ba zy,a b
88
Function
OptimizationExample
f = g(x) + g(x)
89
The Real WOrld
90
No time for:Polymorphism
Lists
Tuples
Guards
Accumulators
Continuations
Comprehensions
Fault Tolerance
Type Systems
Process Linking
Recursion (TCO)
Higher Order Functions
91
Summary
92
Functions (Math)
93
Functions (Math)
Immutability
94
Functions (Math)
Immutability
Concurrency
95
Functions (Math)
Immutability
Concurrency
Developer
Optimizations
96
Functions (Math)
Immutability Side Effects
Concurrency
Developer
Optimizations
97
Functions (Math)
Immutability Side Effects
Concurrency
Developer
Optimizations
Monads
98
Functions (Math)
Immutability Side Effects
Concurrency Monads
Developer
Optimizations
Automated
Optimizations
99
Things should not change
(but state is great!) and they should
not affect others
(without notifying us)100
100
and it would be good if they
could do both at the
same time
(all the time)
101
101
Resources
102
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
The Webhttp://www.erlang.org
http://www.haskell.org
http://www.clojure.org
http://www.trapexit.org
http://www.scala-lang.org
http://lambda-the-ultimate.org
http://pragmaticstudio.com/erlang
http://en.wikibooks.org/wiki/Haskell
http://book.realworldhaskell.org/read
http://www.lisperati.com/fringedc.html
http://research.microsoft.com/fsharp/fsharp.aspx
104
IRC
chat.freenode.net
#haskell
#scala
#erlang
#clojure
#fsharp
105
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
Questions?
107