2. 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.
|
3. FunctionalProgramming-Egypt-2010.nb 3
The Function
Functions in Mathematics
Function Definition
A Function f is a mapping from the domain X to the co-domain Y and is defined by
f : X Y
The curve y 2 x4 x2 1 can be defined as function by the triple notation
, , x, x4 x2 1 : x (1)
where is the domain of real numbers and also the co-domain, alternatively,
f: , x x4 x2 1 (2)
A more common notation is
f x x4 x2 1 (3)
Plotting a Function
Mathematica supports both function and curve plotting
5. FunctionalProgramming-Egypt-2010.nb 5
Curve Plot
In[2]:= ContourPlot y2 x4 x2 1, x, 3, 3 , y, 3, 3 ,
Axes True, Frame False, ContourStyle Thick , AxesLabel x, y
y
3
2
1
Out[2]=
x
3 2 1 1 2 3
1
2
3
Functional Programming Languages
Functional Programming Languages has always been the natural choice for implementing computer derived solutions for mathematical
problems including Numerical Analysis, Combinatorics and Algorithms
Haskell
Implementation of the Quick Sort algorithm in Haskell. Demonstrates polymorphic types, pattern matching, list comprehension and
immutability
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
where
lesser = [ y | y <- xs, y < p ]
greater = [ y | y <- xs, y >= p ]
Scala
Implementation of the Quick Sort algorithm in Scala. Demonstrates polymorphic types, pattern matching, object-oriented support and partial
functions application
def qsort[T <% Ordered[T]](list:List[T]):List[T] = {
list match {
case Nil Nil
case p::xs
val (lesser,greater) = xs partition (_ <= p)
qsort(lesser) ++ (p :: qsort(greater))
}
}
6. 6 FunctionalProgramming-Egypt-2010.nb
def qsort[T <% Ordered[T]](list:List[T]):List[T] = {
list match {
case Nil Nil
case p::xs
val (lesser,greater) = xs partition (_ <= p)
qsort(lesser) ++ (p :: qsort(greater))
}
}
Mathematica
Implementation of the Quick Sort algorithm in Mathematica. Demonstrates pattern matching, pattern guards and rule based programming
In[3]:= ClearAll qsort ;
qsort : ;
qsort p_, xs___ :
Cases xs , y_ ; y p , Cases xs , y_ ; y p .
lesser_, greater_
qsort lesser , p, qsort greater Flatten
In[6]:= qsort 0, 9, 1, 8, 3, 6, 2, 7, 5, 4
Out[6]= 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
|
7. FunctionalProgramming-Egypt-2010.nb 7
Functions in Mathematica
Numeric Computations
Numeric computations through function calls
In[210]:= Plus 1, Exp Times I , Pi
Out[210]= 0
Or through Mathematical notation
Π
In[8]:= 1
Out[8]= 0
Arbitrary precision
In[9]:= N Π, 100
Out[9]= 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068
Calculus
Symbolic Calculus
1
In[10]:= Θ
Sin Θ
1 Π
Out[10]= 2 EllipticF Θ , 2
2 2
Accurate results
In[11]:= Θ FullSimplify
1
Out[11]=
Sin Θ
Algorithms
Optimized algorithms
8. 8 FunctionalProgramming-Egypt-2010.nb
In[12]:= Timing Sort RandomInteger 1, 10 000 000 , 100 000 Short
Out[12]//Short=
0.04, 9, 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 n . RSolve T n T 1, T 1 1 , T n , n
3
Log n
Out[13]= 1
3
Log
2
Graphics
Stunning graphics
In[236]:=
ParametricPlot3D Cos Φ Sin Θ , Sin Φ Sin Θ , Cos Θ , Φ, 0, 2 Π ,
Θ, 0, Π , PlotPoints 100, Mesh None, ColorFunction x, y, z, Φ, Θ Hue ,
ColorFunctionScaling False, Boxed False, Axes False Magnify , .5 & &
Θ Φ Θ Φ
Sin Θ Cos Θ , Sin Φ Cos Φ , Sin Θ Φ Cos Θ Φ , , ,
Partition , 3 & Grid
Out[236]=
|
9. FunctionalProgramming-Egypt-2010.nb 9
Define Your Own Function
A Function as a Rule
Functions can be defined as a delayed assignment rule
In[15]:= f x_ : x3 x 1
Functions can accept multiple parameters
In[16]:= f x_, a_, b_ : x3 ax b
10. 10 FunctionalProgramming-Egypt-2010.nb
Calling a Function
Default Form
Default Form, notice the square brackets
In[17]:= f 2
Out[17]= 7
Prefix Form
Prefix Form, using the @ sign
In[18]:= f 2
Out[18]= 7
Postfix Form
Postfix Form, using the // sign
In[19]:= 2Π Sin
Out[19]= 0
Infix Form
Infix Form, function surrounded by ~ sign
In[20]:= 1, 2, 3 Join 4, 5, 6
Out[20]= 1, 2, 3, 4, 5, 6
Multiple Arguments
Function call with multiple actual arguments
12. 12 FunctionalProgramming-Egypt-2010.nb
Domains and Patterns
Domains as Patterns
Domains can be specified as patterns
In[22]:= ClearAll square ;
square i_Integer : i2
2
square i_Real : Floor i
2
square i_Complex : Re i
2
square a_Symbol : a
square SomeDataType a_ : a2
In[28]:= square 2.1 , square 2 , square 2 3 , square x , square SomeDataType x
Out[28]= 4, 4, 4, x2 , x2
Patterns and Lists
Expressive patterns on lists, notice how ordering is important
One or more __ Zero or more ___
2 3
In[29]:= ClearAll listOp ;
listOp :
listOp x_, y_ : y, x flip a tuple
listOp x_, xs__ : xs drop the first element
listOp l : __ ... : Reverse l match a list of lists
In[34]:= listOp 1, 2, 3 , listOp 1, 2 , listOp 1, 2 , 3, 4
Out[34]= 2, 3 , 2, 1 , 3, 4 , 1, 2
|
13. FunctionalProgramming-Egypt-2010.nb 13
Guards on Patterns
Guards on Domains
Guards can be specified using the Pattern ? Predicate notation
In[35]:= ClearAll collatz ;
collatz n_Integer ? EvenQ : n 2 Matches only even integers
collatz n_Integer : 3 n 1 Matches all integers
In[38]:= collatz 3 , collatz 4
Out[38]= 10, 2
Arbitrary Conditions
A condition can be specified on a pattern using Pattern /; Predicate notation
Example : Bubble Sort
By Dr Jon D Harrop, 2010 (Modified)
Using pattern matching and conditions on patterns, bubble sort can then be defines as
In[39]:= bubbleSort xs___, x_, y_, ys___ : bubbleSort xs, y, x, ys ; x y
For example
In[40]:= bubbleSort 3, 2, 1
Out[40]= bubbleSort 1, 2, 3
We can simply extract the sorted list using the rule
In[211]:= bubbleSort 3, 2, 1 . _ sorted_ sorted
Out[211]= 1, 2, 3
|
14. 14 FunctionalProgramming-Egypt-2010.nb
Pure Functions
Defining a Pure Function
The Notation
A function that squares its argument
In[41]:= x x2
2
Out[41]= Function x, x
Square function applied at 3
In[42]:= x x2 3
Out[42]= 9
A function with a list as its argument
In[43]:= x, y x2 y2 3, 4
Out[43]= 5
The (# &) Notation
The notation is programmatically equivalent to the notation
Square function applied at 3
2
In[44]:= & 3
Out[44]= 9
A pure function with 2 arguments, notice the numbering after #
In[45]:= 12 22 & 3, 4
Out[45]= 5
15. FunctionalProgramming-Egypt-2010.nb 15
Higher-Order Functions
Map
Map as a function call
In[46]:= Map x x2 , a, b, c, d
Out[46]= a2 , b2 , c2 , d2
Using the ( /@ ) Notation
In[47]:= x x2 a, b, c, d
Out[47]= a2 , b2 , c2 , d2
The mapped function can be composed of any type of expression
In[48]:= Mean , Variance , PDF , x &
NormalDistribution Μ, Σ , MaxwellDistribution Σ , GammaDistribution Α, Β
x2
x Μ 2 2 x
2 Σ2 x2
2 Σ2 2 8 3 Π Σ2 Π Β x 1 Α Β Α
2 2
Out[48]= Μ, Σ , , 2 Σ, , , Α Β, Α Β ,
2Π Σ Π Π Σ3 Gamma Α
Or a composed function
In[215]:= ChemicalData "Caffeine", Magnify , .5 & &
"CHColorStructureDiagram", "CHStructureDiagram", "ColorStructureDiagram", "StructureDiagram",
"MoleculePlot", "SpaceFillingMoleculePlot" Partition , 3 & Grid , Frame All &
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
Or used inside a manipulation
16. 16 FunctionalProgramming-Egypt-2010.nb
Or used inside a manipulation
In[50]:= ClearAll tux, browsers ;
tux, browsers , , , ;
Manipulate
Map
ImageCompose tux, ImageResize , Scaled scale , horizontal, vertical &, browsers
GraphicsRow,
scale, 0.5, 1 ,
horizontal, 60, 200, 10 ,
vertical, 60, 200, 10
scale
horizontal
vertical
Out[52]=
Select
In[53]:= Select 1, 3, 2, 5, 0 , n 0 n
Out[53]= 3, 5
Fold
In[54]:= Fold x, y x y, 0, a, b, c, d
Out[54]= a b c d
Folding to the left or to the right
17. FunctionalProgramming-Egypt-2010.nb 17
In[218]:= Manipulate
Fold F 1, 2 &, x, Take a, b, c, d , step
TreeForm , AspectRatio 1.2, PlotLabel "Fold Left" &,
Fold F 2, 1 &, x, Take a, b, c, d , step
TreeForm , AspectRatio 1.2, PlotLabel "Fold Right" &
GraphicsRow Magnify , 1 &,
step, 0, 4, 1
step
Fold Left Fold Right
F F
Out[218]= F d d F
F c c F
F b b F
x a a x
Power Set
In[56]:= Fold set, element set Append element & set , , Α, Β, Γ
Out[56]= , Α , Β , Γ , Α, Β , Α, Γ , Β, Γ , Α, Β, Γ
One more time
In[57]:= FoldList set, element set Append element & set , , Α, Β, Γ Column
, Α
Out[57]= , Α , Β , Α, Β
, Α , Β , Γ , Α, Β , Α, Γ , Β, Γ , Α, Β, Γ
NestWhileList
x
In[58]:= NestWhileList x , 32, i i 1
2
Out[58]= 32, 16, 8, 4, 2, 1
Pascal Triangle
Pascal triangle can be defined using binomials
18. 18 FunctionalProgramming-Egypt-2010.nb
In[59]:= Table Binomial n, k , n, 0, 4 , k, 0, n Column , Center &
1
1, 1
Out[59]= 1, 2, 1
1, 3, 3, 1
1, 4, 6, 4, 1
This can defined using the pattern
In[60]:= tuples x_ :
tuples x_, y_, ys___ : x y Join tuples y, ys
pascal h_ : NestWhileList 1 Join tuples Join 1 &, 1 , Length h &
pascal 9 Column , Center &
1
1, 1
1, 2, 1
1, 3, 3, 1
Out[63]= 1, 4, 6, 4, 1
1, 5, 10, 10, 5, 1
1, 6, 15, 20, 15, 6, 1
1, 7, 21, 35, 35, 21, 7, 1
1, 8, 28, 56, 70, 56, 28, 8, 1
And nicely manipulated,
In[64]:= ClearAll hexagon, render ;
2Πk 2Πk
hexagon x_, y_ : Polygon Table Sin x, Cos y , k, 6
6 6
Length l
render l_List : Graphics Hue , hexagon 0, 0 , Text Style , White, Bold, 10 & l
Π
GraphicsRow , ImageSize 50 Length , 30 , Spacings 2, 0 &
Manipulate
Graphics render & pascal h GraphicsColumn , Alignment Center, Spacings 0, 8 &
Magnify , 1.5 &,
h, 1, 5, 1
h
1
1 1
Out[67]=
1 2 1
1 3 3 1
1 4 6 4 1
3 n + 1 Problem
19. FunctionalProgramming-Egypt-2010.nb 19
3 n + 1 Problem
n 2 EvenQ n
In[68]:= collatz : n ∂
3n 1 OddQ n
NestWhileList collatz, 200, m m 1
Out[69]= 200, 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 2 &, NestWhileList collatz, x, m m 1 ,
x, 10, 100, 10
x
Out[70]= 70 35 106 53 160
, , , , ,
80 40 20 10 5 16 8 4 2 1
, , , , , , , , ,
|
20. 20 FunctionalProgramming-Egypt-2010.nb
Example: Binary Search Tree
Haskell
Haskell approach to Algebraic Data Types and Pattern Matching
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
The same algorithm in Mathematica syntax
In[71]:= ClearAll tree, insert, inorder, bst ;
tree nil node _, _, _ ;
insert n_, nil : node nil, n, nil ;
insert n_, node l_, x_, r_ ; n x : node insert n , l , x , r ;
insert n_, node l_, x_, r_ : node l, x, insert n, r ;
inorder nil : ;
inorder node l_, x_, r_ : inorder l Join x Join inorder r ;
bst : nil
bst x_, xs___ : Fold insert 2, 1 & , insert x, nil , xs ;
In[80]:= inorder bst 8, 3, 10, 1, 6, 9, 12, 4, 7, 13, 11
Out[80]= 1, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13
Visualizing a Binary Search Tree
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[81]:= bst 8, 3, 10, 1, 6
Out[81]= node node node nil, 1, nil , 3, node nil, 6, nil , 8, node nil, 10, nil
We can then define
21. FunctionalProgramming-Egypt-2010.nb 21
In[82]:= ClearAll tuple ;
tuple nil :
tuple node nil, x_, nil :
tuple node l : node _, a_, _ , x_, nil : tuple l Join x a
tuple node nil, x_, r : node _, b_, _ : x b Join tuple r
tuple node l : node _, a_, _ , x_, r : node _, b_, _ :
tuple l Join x a, x b Join tuple r
Then
In[88]:= tuple bst 8, 3, 10, 1, 6, 9, 12, 4, 7, 13, 11
Out[88]= 3 1, 3 6, 6 4, 6 7, 8 3, 8 10, 10 9, 10 12, 12 11, 12 13
Plotting the BST
In[89]:= TreePlot tuple bst 8, 3, 10, 1, 0, 4, 6, 5, 9, 12, 2, 7, 13, 11 ,
Automatic, 8, VertexLabeling True, DirectedEdges True,
PlotLabel " 8,3,10,1,0,4,6,5,9,12,2,7,13,11 ", VertexRenderingFunction
ps, v White, EdgeForm Black, Thick , Disk ps, .2 , Black, Text v, ps
8,3,10,1,0,4,6,5,9,12,2,7,13,11
8
3 10
Out[89]=
1 4 9 12
0 2 6 11 13
5 7
We can then visualize a random BST construction step by step
22. 22 FunctionalProgramming-Egypt-2010.nb
In[214]:= With l RandomInteger 1, 100 , 10 DeleteDuplicates ,
Manipulate
Text Style Framed l , 12, Bold, Black ,
TreePlot
tuple bst Take l, step ,
Automatic, l 1 , VertexLabeling True, DirectedEdges True, VertexRenderingFunction
ps, v White, EdgeForm Black, Thick , Disk ps, .2 , Black, Text v, ps ,
ImageSize 400, 300 , ImagePadding 1
,
Text Style Framed inorder bst Take l, step , 12, Bold, Blue
Column , Center &,
step, 2, Length l , 1
step
91, 57, 43, 99, 92, 50, 11, 48, 89
91
57 99
Out[214]=
43 92
11 50
48
11, 43, 48, 50, 57, 91, 92, 99
|
23. FunctionalProgramming-Egypt-2010.nb 23
Pattern Matching and Transformation
Matching Cases
Match Cases
In[91]:= Cases a2 , b3 , c4 , d5 , e6 , _2
Out[91]= a2
Match Cases with a predicate
In[92]:= Cases a2 , b3 , c4 , d5 , e6 , _n_ ; EvenQ n
Out[92]= a2 , c4 , e6
Match Cases with a predicate and a transformation rule
In[93]:= Cases a2 , b3 , c4 , d5 , e6 , x_n_ ; OddQ n xn 1
Out[93]= b4 , d6
Pattern Matching and Rules
Swap is simple
In[94]:= a, b . x_, y_ y, x
Out[94]= b, a
Decompose an expression
In[95]:= x Sin Θ y Cos Θ . a_ Sin Α_ b_ Cos Α_ a, b, Α
Out[95]= x, y, Θ
Match rules
24. 24 FunctionalProgramming-Egypt-2010.nb
In[96]:= ClearAll g ;
g
Μ Α, Μ Β,
Α i, Α j,
Β a, Β b
;
GraphPlot g, VertexLabeling True, AspectRatio 0.2 Magnify , 1.5 &
i b
Out[98]= Α Μ Β
j a
Use delayed rules
In[99]:= find the children of the vertex Β in the Graph g
. Β x_ x , _ & g Flatten
Out[99]= a, b
Example: Palindrome
Generate a sequence of probable palindrome integers
In[100]:= alg196 n_Integer : n IntegerDigits n Reverse FromDigits
NestWhileList alg196, 77, 10 000 000 &
Out[101]= 77, 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
Recursively test if a sequence is a palindrome
In[102]:= isPalindrome seq_List : seq .
x_ True,
x_, xs___, y_ x y && isPalindrome xs
Test the sequence
In[103]:= Select NestWhileList alg196, 77, 10 000 000 & , isPalindrome IntegerDigits &
Out[103]= 77, 1111, 2222, 4444, 8888, 661 166, 3 654 563
Example: Run Length Encoding
Perform run length encoding on a finite sequence
By Frank Zizza, 1990
Use replace repeated (//.)
25. FunctionalProgramming-Egypt-2010.nb 25
In[104]:= runLengthEncoding l_List : Map , 1 &, l .
head___, x_, n_ , x_, m_ , tail___ head, x, n m , tail
In[105]:= runLengthEncoding a, a, a, b, b, c, c, c, c, a, a
Out[105]= a, 3 , b, 2 , c, 4 , a, 2
How does the magic happen?
First define the magical rule
In[106]:= ClearAll rule ;
rule head___, x_, n_ , x_, m_ , tail___ head, x, n m , tail ;
Second, generate a list tuples of the form e1 , 1 , e2 , 1 , ..., en , 1
In[108]:= Map , 1 &, a, a, a, b, b, c, c, c
Out[108]= a, 1 , a, 1 , a, 1 , b, 1 , b, 1 , c, 1 , c, 1 , c, 1
Keep applying the transformation until the input is exhausted
In[109]:= . rule
Out[109]= a, 2 , a, 1 , b, 1 , b, 1 , c, 1 , c, 1 , c, 1
|
26. 26 FunctionalProgramming-Egypt-2010.nb
Example: Mathematica in Bioinformatics
XML in Mathematica
Mathematica supports a large variety of data formats, XML happens to be one of them
In[225]:= xml Import " work presentation Mathematica Conference 2010 code xml graph.xml", "XML"
Out[225]= XMLObject Document ,
XMLElement v, id root , XMLElement v, id a , XMLElement v, id a1, cost 1 , ,
XMLElement v, id a2, cost 2 , , XMLElement v, id a3, cost 3 , ,
XMLElement v, id b , XMLElement v, id b1, cost 4 , , XMLElement v, id b2, cost 5 , ,
XMLElement v, id b3, cost 6 , , XMLElement v, id c , XMLElement v, id c1, cost 7 , ,
XMLElement v, id c2, cost 8 , , XMLElement v, id c3, cost 9 , ,
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
In[226]:= ClearAll root, id, cost, rec ;
root XMLObject _ _, r_, _ : r
id XMLElement _, as_, ___ : "id" . as
cost XMLElement _, as__ , ___ : "cost" . as, _ "0"
rec e : XMLElement "v", _, cs : ___ :
id e id , cost & cs Join rec cs Flatten , 1 &
Recursively walk the element structure and create a Mathematica graph representation
In[231]:= rec root xml
Out[231]= root a, 0 , root b, 0 , root c, 0 , a a1, 1 , a a2, 2 ,
a a3, 3 , b b1, 4 , b b2, 5 , b b3, 6 , c c1, 7 , c c2, 8 , c c3, 9
Plot the extracted graph
27. FunctionalProgramming-Egypt-2010.nb 27
In[232]:= rec root xml GraphPlot , VertexLabeling True, EdgeLabeling True & Magnify , 1 &
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[118]:= xml Import " work presentation Mathematica Conference 2010 code xml sequenceML.xml", "XML" ;
In[119]:= ClearAll root, sequenceList, sequence, element ;
root XMLObject _ _, r_, _ : r
sequenceList XMLElement "sequenceML", _, seqs_ : sequence seqs
sequence e : XMLElement "sequence", "seqID" id_ , cs_ :
seqID id,
name element "name", cs ,
description element "description", cs ,
aminoAcidSequence element "aminoAcidSequence", cs
element name_, elements_ :
Cases elements, XMLElement n_, , value_ ;n name value First
In[124]:= root xml sequenceList First
Out[124]= seqID gi 58374180 gb AAW72226.1 , name HA,
description Influenza A virus A duck Shandong 093 2004 H5N1 , aminoAcidSequence
MEEIVLLLAIVSLVKSDQICIGYHANNSTEQVDTIMEKNVTVTHAQDILEKTHNGKLCDLDGVKPLILRDCSVAGWLLGNPMCDEFINVPEWSYIVEKANPAND
LCYPGDFNDYEELKHLLSRINHFEKIQIIPKSSWSDHEASSGVSSACPYNGKSSFFRNVVWLIKKNSSYPTIKRSYNNTNQEDLLILWGIHHPNDAAE
QTKLYQNPTTYISVGTSTLNQRLVPKIATRSKVNGQSGRMEFFWTILKPNDAINFESNGNFIAPEYAYKIVKKGDSAIMKSELEYGNCNTKCQTPMGA
INSSMPFHNIHPLTIGECPKYVKSNRLVLATGLRNTPQRERRRKKRGLFGAIAGFIEGGWQGMVDGWYGYHHSNEQGSGYAADKESTQKAIDGVTNKV
NSIIDKMNTQFEAVGREFNNLERRIENLNKKMEDGFLDVWTYNAELLVLMENERTLDFHDSNVKNLYDKVRLQLRDNAKELGNGCFEFYHKCDNECME
SVKNGTYDYPRYSEEARLNREEISGVKLESMGTYQILSIYSTVASSLALAIMVAGLSLWMCSNGSLQCRICI
28. 28 FunctionalProgramming-Egypt-2010.nb
In[125]:= first, last root xml sequenceList . x_, ___, y_ x, y
Out[125]= seqID gi 58374180 gb AAW72226.1 , name HA,
description Influenza A virus A duck Shandong 093 2004 H5N1 , aminoAcidSequence
MEEIVLLLAIVSLVKSDQICIGYHANNSTEQVDTIMEKNVTVTHAQDILEKTHNGKLCDLDGVKPLILRDCSVAGWLLGNPMCDEFINVPEWSYIVEKANPA
NDLCYPGDFNDYEELKHLLSRINHFEKIQIIPKSSWSDHEASSGVSSACPYNGKSSFFRNVVWLIKKNSSYPTIKRSYNNTNQEDLLILWGIHHPN
DAAEQTKLYQNPTTYISVGTSTLNQRLVPKIATRSKVNGQSGRMEFFWTILKPNDAINFESNGNFIAPEYAYKIVKKGDSAIMKSELEYGNCNTKC
QTPMGAINSSMPFHNIHPLTIGECPKYVKSNRLVLATGLRNTPQRERRRKKRGLFGAIAGFIEGGWQGMVDGWYGYHHSNEQGSGYAADKESTQKA
IDGVTNKVNSIIDKMNTQFEAVGREFNNLERRIENLNKKMEDGFLDVWTYNAELLVLMENERTLDFHDSNVKNLYDKVRLQLRDNAKELGNGCFEF
YHKCDNECMESVKNGTYDYPRYSEEARLNREEISGVKLESMGTYQILSIYSTVASSLALAIMVAGLSLWMCSNGSLQCRICI ,
seqID gi 108671045 gb ABF93441.1 , name hemagglutinin,
description Influenza A virus St Jude H5N1 influenza seed virus 163222 , aminoAcidSequence
MEKIVLLLAIVSLVKSDQICIGYHANNSTEQVDTIMEKNVTVTHAQDILEKTHNGKLCDLDGVKPLILRDCSVAGWLLGNPMCDEFLNVPEWSYIVEKINPA
NDLCYPGNFNDYEELKHLLSRINHFEKIQIIPKSSWSDHEASSGVSSACPYQGRSSFFRNVVWLIKKNNAYPTIKRSYNNTNQEDLLVLWGIHHPN
DAAEQTRLYQNPTTYISVGTSTLNQRLVPKIATRSKVNGQSGRMEFFWTILKPNDAINFESNGNFIAPENAYKIVKKGDSTIMKSELEYGNCNTKC
QTPIGAINSSMPFHNIHPLTIGECPKYVKSNRLVLATGLRNSPQIETRGLFGAIAGFIEGGWQGMVDGWYGYHHSNEQGSGYAADKESTQKAIDGV
TNKVNSIIDKMNTQFEAVGREFNNLERRIENLNKKMEDGFLDVWTYNAELLVLMENERTLDFHDSNVKNLYDKVRLQLRDNAKELGNGCFEFYHRC
DNECMESVRNGTYDYPQYSEEARLKREEISGVKLESIGTYQILSIYSTVASSLALAIMVAGLSLWMCSNGSLQCRICI
In[126]:= SequenceAlignment aminoAcidSequence . first, aminoAcidSequence . last
Out[126]= ME, E, K , IVLLLAIVSLVKSDQICIGYHANNSTEQVDTIMEKNVTVTHAQDILEKTHNGKLCDLDGVKPLILRDCSVAGWLLGNPMCDEF,
I, L , NVPEWSYIVEK, A, I , NPANDLCYPG, D, N , FNDYEELKHLLSRINHFEKIQIIPKSSWSDHEASSGVSSACPY,
N, Q , G, K, R , SSFFRNVVWLIKKN, SS, NA , YPTIKRSYNNTNQEDLL, I, V , LWGIHHPNDAAEQT, K, R ,
LYQNPTTYISVGTSTLNQRLVPKIATRSKVNGQSGRMEFFWTILKPNDAINFESNGNFIAPE, Y, N , AYKIVKKGDS, A, T ,
IMKSELEYGNCNTKCQTP, M, I , GAINSSMPFHNIHPLTIGECPKYVKSNRLVLATGLRN, T, S , PQ, R, I , E, RRRKK, T ,
RGLFGAIAGFIEGGWQGMVDGWYGYHHSNEQGSGYAADKESTQKAIDGVTNKVNSIIDKMNTQFEAVGREFNNLERRIENLNKKMEDGFLDVWTYNAELLVLMEN
ERTLDFHDSNVKNLYDKVRLQLRDNAKELGNGCFEFYH, K, R , CDNECMESV, K, R , NGTYDYP,
R, Q , YSEEARL, N, K , REEISGVKLES, M, I , GTYQILSIYSTVASSLALAIMVAGLSLWMCSNGSLQCRICI
|
29. FunctionalProgramming-Egypt-2010.nb 29
Example: Mathematica XQuery
XQuery
A fluent XML Query Language from W3C
XQuery FLWOR Expression
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
Mathematica XML Support
Import the XML document
In[127]:= xml Import " work presentation Mathematica Conference 2010 xml books.xml", "XML"
Out[127]= XMLObject Document XMLObject Declaration Version 1.0, Encoding ISO 8859 1 ,
XMLElement bookstore, , XMLElement book, category COOKING ,
XMLElement title, lang en , Everyday Italian , XMLElement author, , Giada De Laurentiis ,
XMLElement year, , 2005 , XMLElement price, , 30.00 ,
XMLElement book, category CHILDREN , XMLElement title, lang en , Harry Potter ,
XMLElement author, , J K. Rowling , XMLElement year, , 2005 , XMLElement price, , 29.99 ,
XMLElement book, category WEB , XMLElement title, lang en , XQuery Kick Start ,
XMLElement author, , James McGovern , XMLElement author, , Per Bothner ,
XMLElement author, , Kurt Cagle , XMLElement author, , James Linn , XMLElement author,
, Vaidyanathan Nagarajan , XMLElement year, , 2003 , XMLElement price, , 49.99 ,
XMLElement book, category WEB , XMLElement title, lang en , Learning XML , XMLElement
author, , Erik T. Ray , XMLElement year, , 2003 , XMLElement price, , 39.95 ,
XQuery like DSL in Mathematica
Define an XQuery like Domain Specific Language (DSL) for XML processing using Mathematica's Functional approach
The tiny language is a set of higher - order functions, each function returns a function that can act on the XML axis
30. 30 FunctionalProgramming-Egypt-2010.nb
In[128]:= ClearAll doc, where, orderBy, e, att, attribute, data, return ;
doc XMLObject Document _, root_, _ : root;
where Select;
orderBy Sort;
e n_String : es Cases es, XMLElement n , _, _ , ;
att XMLElement _ , rules_, _ , n_String : n . rules Join _ Φ ;
attribute XMLElement _ , rules_, _ , n_String : n n . rules ;
attribute n_String : es attribute , n & es;
attribute n_String, pred_ : el pred att el, n ;
data n_String : es Cases es, XMLElement n , _, d_ d, ;
data n_String, pred_ : es Cases es, XMLElement n , _, d_ ; pred d , ;
return es_, f_ : f es;
Mathematica XQuery DSL in Action
XPath Expressions
All book titles
In[140]:= doc xml e "book" data "title"
Out[140]= Everyday Italian, Harry Potter, XQuery Kick Start, Learning XML
All book authors
In[141]:= doc xml e "book" data "author"
Out[141]= Giada De Laurentiis, J K. Rowling, James McGovern,
Per Bothner, Kurt Cagle, James Linn, Vaidyanathan Nagarajan, Erik T. Ray
The return function
Return a { {author..} title} tuple
In[142]:= doc xml e "book"
return bs
data "author" . a_ a data "title" . t_ t & bs
Out[142]= Giada De Laurentiis Everyday Italian, J K. Rowling Harry Potter,
James McGovern, Per Bothner, Kurt Cagle, James Linn, Vaidyanathan Nagarajan XQuery Kick Start,
Erik T. Ray Learning XML
The where function
All titles with price > 30
In[143]:= doc xml e "book"
where b b data "price", ToExpression 30 &
return data "title"
Out[143]= XQuery Kick Start, Learning XML
All titles in the COOKING category
31. FunctionalProgramming-Egypt-2010.nb 31
In[144]:= doc xml e "book"
where b b attribute "category", "COOKING" &
return data "title"
Out[144]= Everyday Italian
All titles in the WEB category with price > 40
In[145]:= doc xml e "book"
where b
b data "price", ToExpression 40 & && b attribute "category", "WEB" &
return data "title"
Out[145]= XQuery Kick Start
The order by function
Order by title in descending order
In[146]:= doc xml e "book"
where b b attribute "category", "WEB" &
orderBy Order 1 data "title" , 2 data "title" 0 &
return data "title"
Out[146]= XQuery Kick Start, Learning XML
All books in WEB category, ordered by title in ascending order, formatted as { title price } list
In[147]:= doc xml e "book"
where b b attribute "category", "WEB" &
orderBy Order 1 data "title" , 2 data "title" 0 &
return bs
data "title" . t_ t data "price" . p_ p & bs
Out[147]= Learning XML 39.95, XQuery Kick Start 49.99
|
32. 32 FunctionalProgramming-Egypt-2010.nb
Example: SQL
Establish a Database Connection
In[148]:= HSQL memory db
Needs "DatabaseLink`"
bookstore OpenSQLConnection ;
Create the Book table
In[150]:= SQLDropTable bookstore, & SQLTableNames bookstore ;
SQLCreateTable bookstore, SQLTable "BOOK" ,
SQLColumn "ID", "DataTypeName" "INTEGER" ,
SQLColumn "TITLE", "DataTypeName" "VARCHAR", "DataLength" 128 ,
SQLColumn "YEAR", "DataTypeName" "VARCHAR", "DataLength" 4 ,
SQLColumn "PRICE", "DataTypeName" "FLOAT"
;
SQLTableNames bookstore
Out[152]= BOOK
Load books from XML
In[153]:= ClearAll books ;
books
doc xml e "book" return
bs
data "title" . t_ t,
data "year" . y_ y,
data "price" . p_ p
& bs
Out[154]= Everyday Italian, 2005, 30.00 , Harry Potter, 2005, 29.99 ,
XQuery Kick Start, 2003, 49.99 , Learning XML, 2003, 39.95
Load books into the Database
In[155]:= MapIndexed
SQLInsert bookstore, "BOOK", "ID", "TITLE", "YEAR", "PRICE" , 2 Join 1 &, books ;
Query the Database
In[156]:= SQLSelect bookstore, "BOOK" TableForm
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
Close the Database Connection
34. 34 FunctionalProgramming-Egypt-2010.nb
Example: Geometric Transformation
The RotationTransform Function
Understanding the Function
In[158]:= RotationTransform Θ
Cos Θ Sin Θ 0
Out[158]= TransformationFunction Sin Θ Cos Θ 0
0 0 1
In[159]:= RotationTransform Θ x, y
Out[159]= x Cos Θ y Sin Θ , y Cos Θ x Sin Θ
Creating a Replacement Rule
In[160]:= RotationTransform Θ x, y . a_, b_ x a, y b
Out[160]= x x Cos Θ y Sin Θ , y y Cos Θ x Sin Θ
Testing Our Rule
In[161]:= y x2 . x x Cos Θ y Sin Θ , y y Cos Θ x Sin Θ
2
Out[161]= y Cos Θ x Sin Θ x Cos Θ y Sin Θ
2
In[162]:= y Cos Θ x Sin Θ x Cos Θ y Sin Θ .Θ 90 °
Out[162]= x y2
35. FunctionalProgramming-Egypt-2010.nb 35
In[163]:= ContourPlot y x2 , x y2 , x, 2 Π, 2 Π , y, 2 Π, 2 Π ,
Axes True, Frame False, ContourStyle Thick, Red , Thick, Blue
6
4
2
Out[163]=
6 4 2 2 4 6
2
4
6
Creating a Simple Rotate Function
In[164]:= rotate eq_, Θ_ : eq . RotationTransform Θ x, y . a_, b_ x a, y b
In[165]:= rotate y x2 , 90 ° , rotate y Sin x , 30 ° FullSimplify
1
Out[165]= x y2 , x 3 y 2 Sin 3 x y
2
36. 36 FunctionalProgramming-Egypt-2010.nb
The Rotate Function in Action
In[233]:= Show
ContourPlot
rotate y Sin x , 1 ° Evaluate,
x, 2 Π, 2 Π , y, 2 Π, 2 Π ,
Frame False,
Exclusions rotate y Sin x , 1 ° Evaluate, x2 y2 25 ,
1
ContourStyle Thickness 0.004 , Hue
Π
& Range 0, 360, 10
Magnify , 1 &
Out[233]=
|
37. FunctionalProgramming-Egypt-2010.nb 37
Example: Tree Chains
Graph Algebraic Data Type
Graph Structure and supporting functions
In[167]:= ClearAll Graph, graph, Vertex, vertex, Leaf, leaf,
Branch, tail, branch, succ, dft, concatMap, chains, toRules, vrf ;
Vertex Vertex d$ : _ ;
vertex d_ : Vertex d ;
value Vertex : d$;
Graph Graph rep$ : _Vertex , _Vertex ... ... ;
graph rep : _Vertex , _Vertex ... ... : Graph rep ;
graph rep : _Vertex _Vertex ... ... :
Graph . x_ y : __ x, y & rep ;
rep Graph : rep$;
Leaf Leaf v$ : Vertex ;
leaf v : Vertex : Leaf v ;
vertex Leaf : v$;
Branch Branch v$ : Vertex, tail$ : __ ;
branch v : Vertex, : leaf v ;
branch v : Vertex, l : ___ : Branch v, l ;
vertex Branch : v$;
tail Branch : tail$;
succ g : Graph, v : Vertex : Cases rep g, u : Vertex, adj_ ; u v adj Flatten;
dft g : Graph, v : Vertex : branch v, dft g, & succ g, v ;
concatMap f_, l : __ : Fold Join, , Flatten f & l ;
chains g : Graph : chains dft g, rep g 1 1 ;
chains l : Leaf : vertex l ;
chains b : Branch : concatMap vertex b, &, chains & tail b Flatten , 1 &;
toRules g : Graph : . x_, y : __ x & y & rep g Flatten;
toRules ch : _Vertex ... : ch . x_ , x_, y_, xs___ x y Join toRules y, xs ;
toRules chs : _Vertex ... ... : toRules & chs;
vrf ps, v White, EdgeForm Black , Disk ps, .3 , Black, Text value v, ps ;
Graph Instance
In[193]:= Dynamic g ;
g graph
vertex Μ vertex Α, Β, Γ ,
vertex Α vertex Α1 , Α2 , Α3 ,
vertex Β vertex Β1 , Β2 , Β3 ,
vertex Γ vertex Γ1 , Γ2 , Γ3 ;