Professional Documents
Culture Documents
Functional Programming in Mathematica: An Introduction
Functional Programming in Mathematica: An Introduction
in Mathematica
An Introduction
Hossam Karim
ITWorx
2 FunctionalProgramming-Egypt-2010.nb
About
è Work for an Egyptian Software Services Company
è Design software for the Bioinformatics and Telecommunications industries
è Use Mathematica every day
è Implement prototypes and proof of concepts
è Design and implement solutions and algorithms
è Validate implementations' feasibility, performance and correctness
Code, concepts and algorithms provided in this presentation are not related or affiliated by any means to my employer nor my clients. All the material in this presentations
are samples not suitable for production, and are provided for the sole purpose of demonstration.
¢ | £
FunctionalProgramming-Egypt-2010.nb 3
The Function
Functions in Mathematics
Function Definition
f : X ® Y
where R is the domain of real numbers and also the co-domain, alternatively,
f : R ® R, x Ì ± x4 - x2 + 1 (2)
f HxL = ± x4 - x2 + 1 (3)
Plotting a Function
Mathematica supports both function and curve plotting
4 FunctionalProgramming-Egypt-2010.nb
Function plot
y
3
Out[1]=
x
-3 -2 -1 1 2 3
-1
-2
-3
FunctionalProgramming-Egypt-2010.nb 5
Curve Plot
Out[2]=
x
-3 -2 -1 1 2 3
-1
-2
-3
Haskell
Implementation of the Quick Sort algorithm in Haskell. Demonstrates polymorphic types, pattern matching, list comprehension and
immutability
Scala
Implementation of the Quick Sort algorithm in Scala. Demonstrates polymorphic types, pattern matching, object-oriented support and partial
functions application
Mathematica
Implementation of the Quick Sort algorithm in Mathematica. Demonstrates pattern matching, pattern guards and rule based programming
In[3]:= ClearAll@qsortD;
qsort@8<D := 8<;
qsort@8p_, xs___<D :=
8Cases@8xs<, y_ ; y <= pD, Cases@8xs<, y_ ; y > pD< .
8lesser_, greater_< ®
8qsort@lesserD, p, qsort@greaterD< Flatten
¢ | £
FunctionalProgramming-Egypt-2010.nb 7
Functions in Mathematica
Numeric Computations
Out[210]= 0
In[8]:= 1 + ã-ä Π
Out[8]= 0
Arbitrary precision
Out[9]= 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068
Calculus
Symbolic Calculus
1
In[10]:= á âΘ
Sin@ΘD
1 Π
Out[10]= -2 EllipticFA - Θ , 2E
2 2
Accurate results
In[11]:= ¶Θ % FullSimplify
1
Out[11]=
Sin@ΘD
Algorithms
Optimized algorithms
8 FunctionalProgramming-Egypt-2010.nb
Out[12]//Short=
80.04, 89, 400, 418, 657, 719, 859, 947, 1057, 1061, 99 982,
9 998 951, 9 998 953, 9 999 009, 9 999 077, 9 999 123, 9 999 227, 9 999 236, 9 999 314, 9 999 497<<
Algorithm analysis
2n
In[13]:= T@nD . RSolveA9T@nD TA E + 1, T@1D 1=, T@nD, nE
3
Log@nD
Out[13]= 91 + =
3
LogA E
2
Graphics
Stunning graphics
In[236]:=
HParametricPlot3D@ 8Cos@ ΦD Sin@ΘD, Sin@ΦD Sin@ΘD, Cos@ΘD<, 8Φ, 0, 2 Π<,
8Θ, 0, Π<, PlotPoints ® 100, Mesh ® None, ColorFunction ® H8x, y, z, Φ, Θ< Ì Hue@ðDL,
ColorFunctionScaling ® False, Boxed ® False, Axes ® FalseD Magnify@ð, .5D &L &
9Sin@ΘD Cos@ΘD, Sin@ΦD Cos@ΦD, Sin@Θ + ΦD Cos@Θ + ΦD, ãΘ , ãΦ , ãΘ+Φ =
Partition@ð, 3D & Grid
Out[236]=
¢ | £
FunctionalProgramming-Egypt-2010.nb 9
A Function as a Rule
In[15]:= f@x_D := x3 - x + 1
Calling a Function
Default Form
In[17]:= f@2D
Out[17]= 7
Prefix Form
In[18]:= f2
Out[18]= 7
Postfix Form
In[19]:= 2 Π Sin
Out[19]= 0
Infix Form
Multiple Arguments
Out[223]=
¢ | £
12 FunctionalProgramming-Egypt-2010.nb
Domains as Patterns
In[22]:= ClearAll@squareD;
square@i_IntegerD := i2
square@i_RealD := Floor@iD2
square@i_ComplexD := Re@iD2
square@a_SymbolD := a2
square@SomeDataType@a_DD := a2
2 2
Out[28]= 94, 4, 4, x , x =
One or more __
¨ Zero or more ___
©
2 3
In[29]:= ClearAll@listOpD;
listOp@8<D := 8<
listOp@8x_, y_<D := 8y, x< H* flip a tuple *L
listOp@8x_, xs__<D := 8xs< H* drop the first element *L
listOp@l : 88__< ...<D := Reverse@lD H* match a list of lists *L
In[34]:= 8listOp@81, 2, 3<D, listOp@81, 2<D, listOp@8 81, 2<, 83, 4< <D <
¢ | £
FunctionalProgramming-Egypt-2010.nb 13
Guards on Patterns
Guards on Domains
In[35]:= ClearAll@collatzD;
collatz@n_Integer ? EvenQD := n 2 H* Matches only even integers *L
collatz@n_IntegerD := 3 n + 1 H* Matches all integers *L
Arbitrary Conditions
Using pattern matching and conditions on patterns, bubble sort can then be defines as
For example
¢ | £
14 FunctionalProgramming-Egypt-2010.nb
Pure Functions
The Ì Notation
In[41]:= x Ì x2
2
Out[41]= FunctionAx, x E
In[42]:= Ix Ì x2 M@3D
Out[42]= 9
Out[43]= 5
In[44]:= ð2 &@3D
Out[44]= 9
Out[45]= 5
FunctionalProgramming-Egypt-2010.nb 15
Higher-Order Functions
Map
2 2 2 2
Out[46]= 9a , b , c , d =
2 2 2 2
Out[47]= 9a , b , c , d =
x2
Hx-ΜL2 - 2 x
- ã 2 Σ2 x2 -
ã 2 Σ2 2 H-8 + 3 ΠL Σ2 Π ã Β x-1+Α Β-Α
2 2
Out[48]= 99Μ, Σ , =, 92 Σ, , =, 9Α Β, Α Β , ==
2Π Σ Π Π Σ3 Gamma@ΑD
Or a composed function
H H
O H O H
C C O
H H H H
H H
C C C C
N N
N C N C N
H H N
C H C H
C C C C
N N
O N O N N
O N
H C H H C H
H H
Out[215]=
O
N
N
N
O N
Manipulate@
Map@
ImageCompose@tux, ImageResize@ð, Scaled@scaleDD, 8horizontal, vertical<D &, browsers
D GraphicsRow,
8scale, 0.5, 1<,
8horizontal, 60, 200, 10<,
8vertical, 60, 200, 10<
D
scale
horizontal
vertical
Out[52]=
Select
Fold
Out[54]= a + b + c + d
In[218]:= Manipulate@
8
Fold@F@ð1, ð2D &, x, Take@8a, b, c, d<, stepDD
TreeForm@ð, AspectRatio ® 1.2, PlotLabel ® "Fold Left"D &,
Fold@F@ð2, ð1D &, x, Take@8a, b, c, d<, stepDD
TreeForm@ð, AspectRatio ® 1.2, PlotLabel ® "Fold Right"D &
< GraphicsRow Magnify@ð, 1D &,
8step, 0, 4, 1<
D
step
Out[218]= F d d F
F c c F
F b b F
x a a x
Power Set
In[56]:= Fold@8set, element< Ì set Ü Hð ~ Append ~ element & setL, 88<<, 8Α, Β, Γ<D
Out[56]= 88<, 8Α<, 8Β<, 8Γ<, 8Α, Β<, 8Α, Γ<, 8Β, Γ<, 8Α, Β, Γ<<
In[57]:= FoldList@8set, element< Ì set Ü Hð ~ Append ~ element & setL, 88<<, 8Α, Β, Γ<D Column
88<<
88<, 8Α<<
Out[57]= 88<, 8Α<, 8Β<, 8Α, Β<<
88<, 8Α<, 8Β<, 8Γ<, 8Α, Β<, 8Α, Γ<, 8Β, Γ<, 8Α, Β, Γ<<
NestWhileList
x
In[58]:= NestWhileListAx Ì , 32, i Ì i ¹ 1E
2
Pascal Triangle
In[59]:= Table@Binomial@n, kD, 8n, 0, 4<, 8k, 0, n<D Column@ð, CenterD &
81<
81, 1<
Out[59]= 81, 2, 1<
81, 3, 3, 1<
81, 4, 6, 4, 1<
81<
81, 1<
81, 2, 1<
81, 3, 3, 1<
Out[63]= 81, 4, 6, 4, 1<
81, 5, 10, 10, 5, 1<
81, 6, 15, 20, 15, 6, 1<
81, 7, 21, 35, 35, 21, 7, 1<
81, 8, 28, 56, 70, 56, 28, 8, 1<
1 1
Out[67]=
1 2 1
1 3 3 1
1 4 6 4 1
3 n + 1 Problem
FunctionalProgramming-Egypt-2010.nb 19
3 n + 1 Problem
n2 EvenQ@nD
In[68]:= collatz := n Ì ∂
3 n + 1 OddQ@nD
NestWhileList@collatz, 200, m Ì m ¹ 1D
Out[69]= 8200, 100, 50, 25, 76, 38, 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1<
In[70]:= Manipulate@
MapIndexed@
Text@Style@ð1, Blue, Italic, 45 - ð2DD &, NestWhileList@collatz, x, m Ì m != 1DD,
8x, 10, 100, 10<
D
80 40 20 10 5 16 8 4 2 1
, , , , , , , , , =
¢ | £
20 FunctionalProgramming-Egypt-2010.nb
Haskell
data Tree a =
Empty | Node (Tree a) a (Tree a) deriving(Show, Eq)
insert :: Ord a => a -> Tree a -> Tree a
insert n Empty = Node Empty n Empty
insert n (Node left x right)
| n < x = Node (insert n left) x right
| otherwise = Node left x (insert n right)
inorder :: Ord a => Tree a -> [a]
inorder Empty = []
inorder (Node left x right) =
inorder left ++ [x] ++ inorder right
bst :: Ord a => [a] -> Tree a
bst [] = Empty
bst (x : xs) = foldr(insert) (insert x Empty) xs
Mathematica
inorder@nilD := 8<;
inorder@node@l_, x_, r_DD := inorder@lD ~ Join ~ 8x< ~ Join ~ inorder@rD;
bst@8<D := nil
bst@8x_, xs___<D := Fold@insert@ð2, ð1D & , insert@x, nilD, 8xs<D;
In order to be able to visualize a BST, we need to convert the tree of nodes into a {src ® dst, ...} representation. Using our structure, the
binary search tree of the list {8, 3, 10, 1, 6} is
In[82]:= ClearAll@tupleD;
tuple@nilD := 8<
tuple@node@nil, x_, nilDD := 8<
tuple@node@l : node@_, a_, _D, x_, nilDD := tuple@lD ~ Join ~ 8x ® a<
tuple@node@nil, x_, r : node@_, b_, _DDD := 8x ® b< ~ Join ~ tuple@rD
tuple@node@l : node@_, a_, _D, x_, r : node@_, b_, _DDD :=
tuple@lD ~ Join ~ 8x ® a, x ® b< ~ Join ~ tuple@rD
Then
88,3,10,1,0,4,6,5,9,12,2,7,13,11<
3 10
Out[89]=
1 4 9 12
0 2 6 11 13
5 7
step
91
57 99
Out[214]=
43 92
11 50
48
¢ | £
FunctionalProgramming-Egypt-2010.nb 23
Matching Cases
Match Cases
In[91]:= CasesA9a2 , b3 , c4 , d5 , e6 =, _2 E
2
Out[91]= 9a =
2 4 6
Out[92]= 9a , c , e =
4 6
Out[93]= 9b , d =
Swap is simple
Decompose an expression
Match rules
24 FunctionalProgramming-Egypt-2010.nb
In[96]:= ClearAll@gD;
g = 8
Μ ® Α, Μ ® Β,
Α ® i, Α ® j,
Β ® a, Β ® b
<;
GraphPlot@g, VertexLabeling ® True, AspectRatio ® 0.2D Magnify@ð, 1.5D &
i b
Out[98]= Α Μ Β
j a
Example: Palindrome
Out[101]= 877, 154, 605, 1111, 2222, 4444, 8888, 17 776, 85 547, 160 105, 661 166, 1 322 332, 3 654 563, 7 309 126, 13 528 163<
Out[103]= 877, 1111, 2222, 4444, 8888, 661 166, 3 654 563<
In[106]:= ClearAll@ruleD;
rule = 8head___, 8x_, n_<, 8x_, m_<, tail___< ¦ 8head, 8x, n + m<, tail<;
Second, generate a list tuples of the form 88e1 , 1<, 8e2 , 1<, ..., 8en , 1<<
Out[108]= 88a, 1<, 8a, 1<, 8a, 1<, 8b, 1<, 8b, 1<, 8c, 1<, 8c, 1<, 8c, 1<<
In[109]:= % . rule
Out[109]= 88a, 2<, 8a, 1<, 8b, 1<, 8b, 1<, 8c, 1<, 8c, 1<, 8c, 1<<
¢ | £
26 FunctionalProgramming-Egypt-2010.nb
XML in Mathematica
Mathematica supports a large variety of data formats, XML happens to be one of them
Out[225]= XMLObject@DocumentD@8<,
XMLElement@v, 8id ® root<, 8XMLElement@v, 8id ® a<, 8XMLElement@v, 8id ® a1, cost ® 1<, 8<D,
XMLElement@v, 8id ® a2, cost ® 2<, 8<D, XMLElement@v, 8id ® a3, cost ® 3<, 8<D<D,
XMLElement@v, 8id ® b<, 8XMLElement@v, 8id ® b1, cost ® 4<, 8<D, XMLElement@v, 8id ® b2, cost ® 5<, 8<D,
XMLElement@v, 8id ® b3, cost ® 6<, 8<D<D, XMLElement@v, 8id ® c<, 8XMLElement@v, 8id ® c1, cost ® 7<, 8<D,
XMLElement@v, 8id ® c2, cost ® 8<, 8<D, XMLElement@v, 8id ® c3, cost ® 9<, 8<D<D<D, 8<D
The XML document represents a graph, each vertex v is represented as an element. Children of an element are connected to the parent, the
hierarchy represents the edges. The following functions use Mathematica XML support to create a garph representation of the XML docu-
ment and plot it
Recursively walk the element structure and create a Mathematica graph representation
In[231]:= rec@root@xmlDD
Out[231]= 88root ® a, 0<, 8root ® b, 0<, 8root ® c, 0<, 8a ® a1, 1<, 8a ® a2, 2<,
8a ® a3, 3<, 8b ® b1, 4<, 8b ® b2, 5<, 8b ® b3, 6<, 8c ® c1, 7<, 8c ® c2, 8<, 8c ® c3, 9<<
In[232]:= rec@root@xmlDD GraphPlot@ð, VertexLabeling ® True, EdgeLabeling ® TrueD & Magnify@ð, 1D &
a1 c3
1 9
a2 c2
2 8
a c
0 0
3 root 7
Out[232]=
a3 c1
0
b
4 6
b1 5 b3
b2
Sequence Alignment
In[125]:= 8first, last< = Hroot@xmlD sequenceListL . 8x_, ___, y_< ® 8x, y<
¢ | £
FunctionalProgramming-Egypt-2010.nb 29
XQuery
A fluent XML Query Language from W3C
An XQuery expression is typically a for, let, where, order by and return construct
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
XML in Mathematica
The tiny language is a set of higher - order functions, each function returns a function that can act on the XML axis
30 FunctionalProgramming-Egypt-2010.nb
XPath Expressions
Out[140]= 8Everyday Italian, Harry Potter, XQuery Kick Start, Learning XML<
All books in WEB category, ordered by title in ascending order, formatted as { title ® price } list
¢ | £
32 FunctionalProgramming-Egypt-2010.nb
Example: SQL
Out[152]= 8BOOK<
In[153]:= ClearAll@booksD;
books =
Hdoc@xmlD e@"book"DL ~ return ~
Hbs Ì
8
data@"title"D@ðD . 8t_< ® t,
data@"year"D@ðD . 8y_< ® y,
data@"price"D@ðD . 8p_< ® p
In[155]:= MapIndexed@
SQLInsert@bookstore, "BOOK", 8"ID", "TITLE", "YEAR", "PRICE"<, ð2 ~ Join ~ ð1D &, booksD;
Out[156]//TableForm=
1 Everyday Italian 2005 30.
2 Harry Potter 2005 29.99
3 XQuery Kick Start 2003 49.99
4 Learning XML 2003 39.95
In[157]:= CloseSQLConnection@bookstoreD
¢ | £
34 FunctionalProgramming-Egypt-2010.nb
In[158]:= RotationTransform@ΘD
Cos@ΘD -Sin@ΘD 0
Out[158]= TransformationFunctionA Sin@ΘD Cos@ΘD 0 E
0 0 1
2
Out[161]= y Cos@ΘD + x Sin@ΘD Hx Cos@ΘD - y Sin@ΘDL
2
Out[162]= x y
FunctionalProgramming-Egypt-2010.nb 35
Out[163]=
-6 -4 -2 2 4 6
-2
-4
-6
In[164]:= rotate@eq_, Θ_D := Heq . HRotationTransform@ΘD 8x, y< . 8a_, b_< ® 8x ® a, y ® b<LL
1
2
Out[165]= 9x y , x + 3 y 2 SinA J 3 x - yNE=
2
36 FunctionalProgramming-Egypt-2010.nb
In[233]:= ShowA
ContourPlotA
Hrotate@y Sin@xD, ð1 °DL Evaluate,
8x, -2 Π, 2 Π<, 8y, -2 Π, 2 Π<,
Frame ® False,
Exclusions ® 99rotate@y Sin@xD, ð1 °D Evaluate, x2 + y2 > 25==,
ð1
ContourStyle ® 9Thickness@0.004D, HueA E=
Π
E & Range@0, 360, 10D
E Magnify@ð, 1D &
Out[233]=
¢ | £
FunctionalProgramming-Egypt-2010.nb 37
toRules@g : GraphD := Hð . 88x_, y : 8__<< ¦ HHx ® ðL & yL<L & rep g Flatten;
toRules@ch : 8_VertexT ...<D := ch . 88x_< ¦ 8<, 8x_, y_, xs___< ¦ 8Hx ® yL< ~ Join ~ toRules@8y, xs<D<;
toRules@chs : 88_VertexT ...< ...<D := toRules@ðD & chs;
vrf = 8ps, v< Ì 8White, EdgeForm@BlackD, Disk@ps, .3D, Black, Text@value v, psD<;
Graph Instance
In[193]:= Dynamic@gD;
g = graph@8
8vertex@ΜD ® vertex 8Α, Β, Γ<<,
8vertex@ΑD ® vertex 8Α1 , Α2 , Α3 <<,
8vertex@ΒD ® vertex 8Β1 , Β2 , Β3 <<,
8vertex@ΓD ® vertex 8Γ1 , Γ2 , Γ3 <<<D;
38 FunctionalProgramming-Egypt-2010.nb
Graph Plot
Out[219]= Α Β Γ
Α1 Α2 Α3 Β1 Β2 Β3 Γ1 Γ2 Γ3
Μ Α Α1 Μ Α Α2
Out[220]= Μ Β Β1 Μ Β Β2
Μ Γ Γ1 Μ Γ Γ2
¢ | £
FunctionalProgramming-Egypt-2010.nb 39
Example: Sound
¢ | £