a brief introduction to functional programming
TRANSCRIPT
A brief introduction to functional programming
Sebastian Wild
Stylight GmbH
October 31, 2012
Functional programming languages
Some programming conceptsVariables and FunctionsCurryingFunctions as parametersAccumulators
Advanced examples
Summary
And that language is fast. I mean, really astoundinglyfast, which is why it is so evil. It’s like that psychoticgirlfriend that was amazing in bed. You keep trying tobreak up with her, but she seduces you right back intothat abusive relationship.
from brool.comArticle: The Genius of Python, The Agony of OCaml
Functional programming languages
I PureHaskell, Charity, Clean, Curry, Hope, Miranda
I ImpureErlang, F#, Lisp, ML (Standard ML, OCaml), Scala,Spreadsheets
First program
# p r i n t s t r i n g ” H e l l o , World ! ” ; ;H e l l o , World : u n i t = ( )
Variables and Functions
# l e t a = 5 ; ;v a l a : i n t = 5
# l e t a = 5 + 3 ; ;v a l a : i n t = 8
(∗ ! ! A t t e n t i o n ! ! St rong t y p e system ∗)# l e t a = 5 + 3 . 0 ; ;
Variables and Functions
# l e t a = ( 5 , ( ) , ” H e l l o ” ) ; ;v a l a : i n t ∗ u n i t ∗ s t r i n g = ( 5 , ( ) , ” H e l l o ”)
# l e t f x = x ∗ x ; ;v a l f : i n t −> i n t = <fun>
Currying
# l e t f ( x , y ) = x ∗ y ; ;v a l f : i n t ∗ i n t −> i n t = <fun>
Currying
# l e t f x y = x ∗ y ; ;v a l f : i n t −> i n t −> i n t = <fun>
(∗ Types a r e r i g h t b r a c k e t e d ∗)i n t −> ( i n t −> i n t )
Currying
# l e t f x y = x ∗ y ; ;
# l e t a = f 5 ; ;v a l a : i n t −> i n t = <fun>
# l e t b = a 6 ; ;v a l b : i n t = 30
(∗ F u n c t i o n c a l l s a r e l e f t b r a c k e t e d ∗)# v a l b = ( f 5) 6 ; ;v a l b : i n t = 30
Functions as parameters
# l e t a = [ 1 ; 2 ; 3 ; 4 ] ; ;v a l a : i n t l i s t = [ 1 ; 2 ; 3 ; 4 ]
# l e t r e c map f s =match s w i t h
[ ] −> [ ]| x : : x s −> ( f x ) : : ( map f xs ) ; ;
v a l map : ( ’ a −> ’ b ) −> ’ a l i s t −> ’ b l i s t = <fun>
# l e t b = map ( fun v −> 2 ∗ v ) a ; ;v a l b : i n t l i s t = [ 2 ; 4 ; 6 ; 8 ]
Functions as parameters
L i s t . f o l d l e f t : ( ’ a −> ’ b −> ’ a ) −> ’ a −> ’ b l i s t −> ’ a
L i s t . f o l d l e f t f a [ b1 ; . . . ; bn ]f ( . . . ( f ( f a b1 ) b2 ) . . . )
# L i s t . f o l d l e f t (+) 0 [ 1 ; 2 ; 3 ; 4 ; 5 ; 6 ] ; ;− : i n t = 21
Accumulators
Faculty of n:
# l e t r e c f a c n =i f n <= 0 then 1e l s e n ∗ f a c ( n − 1 ) ; ;
v a l f a c : i n t −> i n t = <fun>
Accumulator
Tail recursive:
# l e t f a c n =l e t r e c fac ’ acc n =
i f n <= 0 then acce l s e fac ’ ( n∗ acc ) ( n−1) i n
fac ’ 1 n ; ;v a l f a c : i n t −> i n t = <fun>
Advanced examples
http://www.ffconsultancy.com/ocaml/bunny/index.htmlhttp://www.ffconsultancy.com/ocaml/ray tracer/index.html
Summary
I No side effects
I Strong type system
I Mathematical functions can be expressed very easily
I Steep learning curve
https://github.com/wildsebastian/AlgorithmsDataStructures