You are on page 1of 39

Functional Programming

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

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 = x 4 - x 2 + 1 can be defined as function by the triple notation

: R, R, : x, ± x4 - x2 + 1 > : x Î R> (1)

where R is the domain of real numbers and also the co-domain, alternatively,

f : R ® R, x Ì ± x4 - x2 + 1 (2)

A more common notation is

f HxL = ± x4 - x2 + 1 (3)

Plotting a Function
Mathematica supports both function and curve plotting
4 FunctionalProgramming-Egypt-2010.nb

Function plot

In[1]:= PlotA9 x4 - x2 + 1 , - x4 - x2 + 1 = , 8x, -3, 3<, PlotRange ® 3,


AspectRatio ® 1, PlotStyle ® 88Black, Thick<<, AxesLabel ® 8x, y<E

y
3

Out[1]=
x
-3 -2 -1 1 2 3

-1

-2

-3
FunctionalProgramming-Egypt-2010.nb 5

Curve Plot

In[2]:= ContourPlotAy2 Š x4 - x2 + 1, 8x, -3, 3<, 8y, -3, 3<,


Axes ® True, Frame ® False, ContourStyle ® 8Thick<, AxesLabel ® 8x, y<E

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 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@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

In[6]:= qsort@80, 9, 1, 8, 3, 6, 2, 7, 5, 4<D

Out[6]= 80, 1, 2, 3, 4, 5, 6, 7, 8, 9<

¢ | £
FunctionalProgramming-Egypt-2010.nb 7

Functions in Mathematica

Numeric Computations

Numeric computations through function calls

In[210]:= Plus@1, Exp@-Times@I , PiDDD

Out[210]= 0

Or through Mathematical notation

In[8]:= 1 + ã-ä Π

Out[8]= 0

Arbitrary precision

In[9]:= N@Π, 100D

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

In[12]:= Timing@Sort@RandomInteger@81, 10 000 000<, 100 000DDD  Short

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

Define Your Own Function

A Function as a Rule

Functions can be defined as a delayed assignment rule

In[15]:= f@x_D := x3 - x + 1

Functions can accept multiple parameters

In[16]:= f@x_, a_, b_D := x3 + a x + b


10 FunctionalProgramming-Egypt-2010.nb

Calling a Function

Default Form

Default Form, notice the square brackets

In[17]:= f@2D

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]:= 81, 2, 3< ~ Join ~ 84, 5, 6<

Out[20]= 81, 2, 3, 4, 5, 6<

Multiple Arguments

Function call with multiple actual arguments


FunctionalProgramming-Egypt-2010.nb 11

In[223]:= Magnify@ChemicalData@"Ethanol", "MoleculePlot"D, 1D

Out[223]=

¢ | £
12 FunctionalProgramming-Egypt-2010.nb

Domains and Patterns

Domains as Patterns

Domains can be specified 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

In[28]:= 8square@2.1D, square@2D, square@2 + 3 äD, square@xD, square@SomeDataType@xDD<

2 2
Out[28]= 94, 4, 4, x , x =

Patterns and Lists

Expressive patterns on lists, notice how ordering is important

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 <

Out[34]= 882, 3<, 82, 1<, 883, 4<, 81, 2<<<

¢ | £
FunctionalProgramming-Egypt-2010.nb 13

Guards on Patterns

Guards on Domains

Guards can be specified using the Pattern ? Predicate notation

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

In[38]:= 8collatz@3D, collatz@4D<

Out[38]= 810, 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@8xs___, x_, y_, ys___<D := bubbleSort@8xs, y, x, ys<D ; x ³ y

For example

In[40]:= bubbleSort@83, 2, 1<D

Out[40]= bubbleSort@81, 2, 3<D

We can simply extract the sorted list using the rule

In[211]:= bubbleSort@83, 2, 1<D . _@sorted_D ® sorted

Out[211]= 81, 2, 3<

¢ | £
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]= FunctionAx, x E

Square function applied at 3

In[42]:= Ix Ì x2 M@3D

Out[42]= 9

A function with a list as its argument

In[43]:= 8x, y< Ì x2 + y2 @3, 4D

Out[43]= 5

The (# &) Notation

The notation is programmatically equivalent to the Ì notation

Square function applied at 3

In[44]:= ð2 &@3D

Out[44]= 9

A pure function with 2 arguments, notice the numbering after #

In[45]:= ð12 + ð22 &@3, 4D

Out[45]= 5
FunctionalProgramming-Egypt-2010.nb 15

Higher-Order Functions

Map

Map as a function call

In[46]:= MapAx Ì x2 , 8a, b, c, d<E

2 2 2 2
Out[46]= 9a , b , c , d =

Using the ( /@ ) Notation

In[47]:= Ix Ì x2 M ž 8a, b, c, d<

2 2 2 2
Out[47]= 9a , b , c , d =

The mapped function can be composed of any type of expression

In[48]:= 8Mean@ðD, Variance@ðD, PDF@ð, xD< & ž


8NormalDistribution@Μ, ΣD, MaxwellDistribution@ΣD, GammaDistribution@Α, Β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

In[215]:= HChemicalData@"Caffeine", ðD  Magnify@ð, .5D &L & ž 8


"CHColorStructureDiagram", "CHStructureDiagram", "ColorStructureDiagram", "StructureDiagram",
"MoleculePlot", "SpaceFillingMoleculePlot"<  Partition@ð, 3D &  Grid@ð, Frame ® AllD &

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 FunctionalProgramming-Egypt-2010.nb

Or used inside a manipulation

In[50]:= ClearAll@tux, browsersD;

8tux, browsers< = 9 , 9 , , ==;

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

In[53]:= Select@8-1, 3, -2, 5, 0<, n Ì 0 < nD

Out[53]= 83, 5<

Fold

In[54]:= Fold@8x, y< Ì x + y, 0, 8a, b, c, d<D

Out[54]= a + b + c + d

Folding to the left or to the right


FunctionalProgramming-Egypt-2010.nb 17

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

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@8set, element< Ì set Ü Hð ~ Append ~ element & ž setL, 88<<, 8Α, Β, Γ<D

Out[56]= 88<, 8Α<, 8Β<, 8Γ<, 8Α, Β<, 8Α, Γ<, 8Β, Γ<, 8Α, Β, Γ<<

One more time

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

Out[58]= 832, 16, 8, 4, 2, 1<

Pascal Triangle

Pascal triangle can be defined using binomials


18 FunctionalProgramming-Egypt-2010.nb

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<

This can defined using the pattern

In[60]:= tuples@8< 8x_<D := 8<


tuples@8x_, y_, ys___<D := 8x + y< ~ Join ~ tuples@8y, ys<D
pascal@h_D := NestWhileList@81< ~ Join ~ tuples@ðD ~ Join ~ 81< &, 81<, Length@ðD < h &D
pascal@9D  Column@ð, CenterD &

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<

And nicely manipulated,

In[64]:= ClearAll@hexagon, renderD;


2Πk 2Πk
hexagon@x_, y_D := PolygonATableA9SinA E + x, CosA E + y=, 8k, 6<EE
6 6
Length@lD
render@l_ListD := GraphicsA9HueA E, hexagon@0, 0D, Text@Style@ð, White, Bold, 10 DD=E & ž l 
ðΠ
GraphicsRow@ð, ImageSize ® 850 * Length@ðD, 30<, Spacings ® 82, 0<D &
Manipulate@
Graphics@Hrender@ðD & ž pascal@hDL  GraphicsColumn@ð, Alignment ® Center, Spacings ® 80, -8<D &D 
Magnify@ð, 1.5D &,
8h, 1, 5, 1<
D

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

n2 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

Out[70]= 70 35 106 53 160


9 , , , , ,

80 40 20 10 5 16 8 4 2 1
, , , , , , , , , =

¢ | £
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, bstD;


tree = nil node@_, _, _D;

insert@n_, nilD := node@nil, n, nilD;


insert@n_, node@l_, x_, r_DD ; n < x := node@Hinsert@n , lDL , x , rD;
insert@n_, node@l_, x_, r_DD := node@l, x, Hinsert@n, rDLD;

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[80]:= inorder ž bst@88, 3, 10, 1, 6, 9, 12, 4, 7, 13, 11<D

Out[80]= 81, 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@88, 3, 10, 1, 6<D

Out[81]= node@node@node@nil, 1, nilD, 3, node@nil, 6, nilDD, 8, node@nil, 10, nilDD

We can then define


FunctionalProgramming-Egypt-2010.nb 21

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

In[88]:= tuple@bst@88, 3, 10, 1, 6, 9, 12, 4, 7, 13, 11<DD

Out[88]= 83 ® 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@88, 3, 10, 1, 0, 4, 6, 5, 9, 12, 2, 7, 13, 11<DD,


Automatic, 8, VertexLabeling ® True, DirectedEdges ® True,
PlotLabel ® "88,3,10,1,0,4,6,5,9,12,2,7,13,11<", VertexRenderingFunction ®
H8ps, v< Ì 8White, EdgeForm@8Black, Thick<D, Disk@ps, .2D, Black, Text@v, psD<LD

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

We can then visualize a random BST construction step by step


22 FunctionalProgramming-Egypt-2010.nb

In[214]:= With@8l = RandomInteger@81, 100<, 10D  DeleteDuplicates<,


Manipulate@
8
Text@Style@Framed@lD, 12, Bold, Black DD,
TreePlot@
tuple ž bst ž Take@l, stepD,
Automatic, l@@1DD, VertexLabeling ® True, DirectedEdges ® True, VertexRenderingFunction ®
H8ps, v< Ì 8White, EdgeForm@8Black, Thick<D, Disk@ps, .2D, Black, Text@v, psD<L,
ImageSize ® 8400, 300<, ImagePadding ® 1
D,
Text@Style@Framed@inorder ž bst ž Take@l, stepDD, 12, Bold, BlueDD
<  Column@ð, CenterD &,
8step, 2, Length@lD, 1<
D
D

step

891, 57, 43, 99, 92, 50, 11, 48, 89<

91

57 99

Out[214]=

43 92

11 50

48

811, 43, 48, 50, 57, 91, 92, 99<

¢ | £
FunctionalProgramming-Egypt-2010.nb 23

Pattern Matching and Transformation

Matching Cases

Match Cases

In[91]:= CasesA9a2 , b3 , c4 , d5 , e6 =, _2 E

2
Out[91]= 9a =

Match Cases with a predicate

In[92]:= CasesA9a2 , b3 , c4 , d5 , e6 =, _n_ ; EvenQ@nDE

2 4 6
Out[92]= 9a , c , e =

Match Cases with a predicate and a transformation rule

In[93]:= CasesA9a2 , b3 , c4 , d5 , e6 =, x_n_ ; OddQ@nD ® xn+1 E

4 6
Out[93]= 9b , d =

Pattern Matching and Rules

Swap is simple

In[94]:= 8a, b< . 8x_, y_< ® 8y, x<

Out[94]= 8b, a<

Decompose an expression

In[95]:= x Sin@ΘD - y Cos@ΘD . Ha_ Sin@Α_D - b_ Cos@Α_DL ® 8a, b, Α<

Out[95]= 8x, y, Θ<

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

Use delayed rules

In[99]:= H* find the children of the vertex Β in the Graph g *L


ð . 8 HΒ ® x_L ¦ 8x< , _ ¦ 8< < & ž g  Flatten

Out[99]= 8a, b<

Example: Palindrome

Generate a sequence of probable palindrome integers

In[100]:= alg196@n_IntegerD := n + HIntegerDigits@nD  Reverse  FromDigitsL


NestWhileList@alg196, 77, ð < 10 000 000 &D

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<

Recursively test if a sequence is a palindrome

In[102]:= isPalindrome@seq_ListD := seq . 8


8< 8x_< ¦ True,
8x_, xs___, y_< ¦ x == y && isPalindrome@8xs<D
<

Test the sequence

In[103]:= Select@NestWhileList@alg196, 77, ð < 10 000 000 &D, isPalindrome@IntegerDigits@ðDD &D

Out[103]= 877, 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 (//.)


FunctionalProgramming-Egypt-2010.nb 25

In[104]:= runLengthEncoding@l_ListD := Map@8ð, 1< &, lD .


8head___, 8x_, n_<, 8x_, m_<, tail___< ¦ 8head, 8x, n + m<, tail<

In[105]:= runLengthEncoding@8a, a, a, b, b, c, c, c, c, a, a<D

Out[105]= 88a, 3<, 8b, 2<, 8c, 4<, 8a, 2<<

How does the magic happen?

First define the magical rule

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<<

In[108]:= Map@8ð, 1< &, 8a, a, a, b, b, c, c, c<D

Out[108]= 88a, 1<, 8a, 1<, 8a, 1<, 8b, 1<, 8b, 1<, 8c, 1<, 8c, 1<, 8c, 1<<

Keep applying the transformation until the input is exhausted

In[109]:= % . rule

Out[109]= 88a, 2<, 8a, 1<, 8b, 1<, 8b, 1<, 8c, 1<, 8c, 1<, 8c, 1<<

¢ | £
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"D

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

In[226]:= ClearAll@root, id, cost, recD;


root@XMLObject@_D@_, r_, _DD := r
id@XMLElement@_, as_, 8___<DD := "id" . as
cost@XMLElement@_, 8as__<, 8___<DD := "cost" . 8as, _ ® "0"<
rec@e : XMLElement@"v", _, cs : 8___<DD :=
H8id ž e ® id ž ð, cost ž ð< & ž HcsLL ~ Join ~ Hrec ž cs  Flatten@ð, 1D &L

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<<

Plot the extracted graph


FunctionalProgramming-Egypt-2010.nb 27

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[118]:= xml = Import@"~workpresentationMathematica-Conference-2010codexmlsequenceML.xml", "XML"D;

In[119]:= ClearAll@root, sequenceList, sequence, elementD;


root@XMLObject@_D@_, r_, _DD := r
sequenceList@XMLElement@"sequenceML", _, seqs_DD := sequence ž seqs
sequence@e : XMLElement@"sequence", 8"seqID" ® id_<, cs_DD :=
8
seqID ® id,
name ® element@"name", csD,
description ® element@"description", csD,
aminoAcidSequence ® element@"aminoAcidSequence", csD
<
element@name_, elements_D :=
Cases@elements, HXMLElement@n_, 8<, 8value_<D ; n === name ® valueLD  First

In[124]:= root@xmlD  sequenceList  First

Out[124]= 8seqID ® giÈ58374180ÈgbÈAAW72226.1È, name ® HA,


description ® Influenza A virus HAduckShandong0932004HH5N1LL, aminoAcidSequence ®
MEEIVLLLAIVSLVKSDQICIGYHANNSTEQVDTIMEKNVTVTHAQDILEKTHNGKLCDLDGVKPLILRDCSVAGWLLGNPMCDEFINVPEWSYIVEKANPAND„
LCYPGDFNDYEELKHLLSRINHFEKIQIIPKSSWSDHEASSGVSSACPYNGKSSFFRNVVWLIKKNSSYPTIKRSYNNTNQEDLLILWGIHHPNDAAE„
QTKLYQNPTTYISVGTSTLNQRLVPKIATRSKVNGQSGRMEFFWTILKPNDAINFESNGNFIAPEYAYKIVKKGDSAIMKSELEYGNCNTKCQTPMGA„
INSSMPFHNIHPLTIGECPKYVKSNRLVLATGLRNTPQRERRRKKRGLFGAIAGFIEGGWQGMVDGWYGYHHSNEQGSGYAADKESTQKAIDGVTNKV„
NSIIDKMNTQFEAVGREFNNLERRIENLNKKMEDGFLDVWTYNAELLVLMENERTLDFHDSNVKNLYDKVRLQLRDNAKELGNGCFEFYHKCDNECME„
SVKNGTYDYPRYSEEARLNREEISGVKLESMGTYQILSIYSTVASSLALAIMVAGLSLWMCSNGSLQCRICI<
28 FunctionalProgramming-Egypt-2010.nb

In[125]:= 8first, last< = Hroot@xmlD  sequenceListL . 8x_, ___, y_< ® 8x, y<

Out[125]= 88seqID ® giÈ58374180ÈgbÈAAW72226.1È, name ® HA,


description ® Influenza A virus HAduckShandong0932004HH5N1LL, aminoAcidSequence ®
MEEIVLLLAIVSLVKSDQICIGYHANNSTEQVDTIMEKNVTVTHAQDILEKTHNGKLCDLDGVKPLILRDCSVAGWLLGNPMCDEFINVPEWSYIVEKANPA„
NDLCYPGDFNDYEELKHLLSRINHFEKIQIIPKSSWSDHEASSGVSSACPYNGKSSFFRNVVWLIKKNSSYPTIKRSYNNTNQEDLLILWGIHHPN„
DAAEQTKLYQNPTTYISVGTSTLNQRLVPKIATRSKVNGQSGRMEFFWTILKPNDAINFESNGNFIAPEYAYKIVKKGDSAIMKSELEYGNCNTKC„
QTPMGAINSSMPFHNIHPLTIGECPKYVKSNRLVLATGLRNTPQRERRRKKRGLFGAIAGFIEGGWQGMVDGWYGYHHSNEQGSGYAADKESTQKA„
IDGVTNKVNSIIDKMNTQFEAVGREFNNLERRIENLNKKMEDGFLDVWTYNAELLVLMENERTLDFHDSNVKNLYDKVRLQLRDNAKELGNGCFEF„
YHKCDNECMESVKNGTYDYPRYSEEARLNREEISGVKLESMGTYQILSIYSTVASSLALAIMVAGLSLWMCSNGSLQCRICI<,
8seqID ® giÈ108671045ÈgbÈABF93441.1È, name ® hemagglutinin,
description ® Influenza A virus HSt Jude H5N1 influenza seed virus 163222L, aminoAcidSequence ®
MEKIVLLLAIVSLVKSDQICIGYHANNSTEQVDTIMEKNVTVTHAQDILEKTHNGKLCDLDGVKPLILRDCSVAGWLLGNPMCDEFLNVPEWSYIVEKINPA„
NDLCYPGNFNDYEELKHLLSRINHFEKIQIIPKSSWSDHEASSGVSSACPYQGRSSFFRNVVWLIKKNNAYPTIKRSYNNTNQEDLLVLWGIHHPN„
DAAEQTRLYQNPTTYISVGTSTLNQRLVPKIATRSKVNGQSGRMEFFWTILKPNDAINFESNGNFIAPENAYKIVKKGDSTIMKSELEYGNCNTKC„
QTPIGAINSSMPFHNIHPLTIGECPKYVKSNRLVLATGLRNSPQIETRGLFGAIAGFIEGGWQGMVDGWYGYHHSNEQGSGYAADKESTQKAIDGV„
TNKVNSIIDKMNTQFEAVGREFNNLERRIENLNKKMEDGFLDVWTYNAELLVLMENERTLDFHDSNVKNLYDKVRLQLRDNAKELGNGCFEFYHRC„
DNECMESVRNGTYDYPQYSEEARLKREEISGVKLESIGTYQILSIYSTVASSLALAIMVAGLSLWMCSNGSLQCRICI<<

In[126]:= SequenceAlignment@aminoAcidSequence . first, aminoAcidSequence . lastD

Out[126]= 8ME, 8E, K<, IVLLLAIVSLVKSDQICIGYHANNSTEQVDTIMEKNVTVTHAQDILEKTHNGKLCDLDGVKPLILRDCSVAGWLLGNPMCDEF,


8I, L<, NVPEWSYIVEK, 8A, I<, NPANDLCYPG, 8D, N<, FNDYEELKHLLSRINHFEKIQIIPKSSWSDHEASSGVSSACPY,
8N, Q<, G, 8K, R<, SSFFRNVVWLIKKN, 8SS, NA<, YPTIKRSYNNTNQEDLL, 8I, V<, LWGIHHPNDAAEQT, 8K, R<,
LYQNPTTYISVGTSTLNQRLVPKIATRSKVNGQSGRMEFFWTILKPNDAINFESNGNFIAPE, 8Y, N<, AYKIVKKGDS, 8A, T<,
IMKSELEYGNCNTKCQTP, 8M, I<, GAINSSMPFHNIHPLTIGECPKYVKSNRLVLATGLRN, 8T, S<, PQ, 8R, I<, E, 8RRRKK, T<,
RGLFGAIAGFIEGGWQGMVDGWYGYHHSNEQGSGYAADKESTQKAIDGVTNKVNSIIDKMNTQFEAVGREFNNLERRIENLNKKMEDGFLDVWTYNAELLVLMEN„
ERTLDFHDSNVKNLYDKVRLQLRDNAKELGNGCFEFYH, 8K, R<, CDNECMESV, 8K, R<, NGTYDYP,
8R, Q<, YSEEARL, 8N, K<, REEISGVKLES, 8M, I<, GTYQILSIYSTVASSLALAIMVAGLSLWMCSNGSLQCRICI<

¢ | £
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"D

Out[127]= XMLObject@DocumentD@8XMLObject@DeclarationD@Version ® 1.0, Encoding ® ISO-8859-1D<,


XMLElement@bookstore, 8<, 8XMLElement@book, 8category ® COOKING<,
8XMLElement@title, 8lang ® en<, 8Everyday Italian<D, XMLElement@author, 8<, 8Giada De Laurentiis<D,
XMLElement@year, 8<, 82005<D, XMLElement@price, 8<, 830.00<D<D,
XMLElement@book, 8category ® CHILDREN<, 8XMLElement@title, 8lang ® en<, 8Harry Potter<D,
XMLElement@author, 8<, 8J K. Rowling<D, XMLElement@year, 8<, 82005<D, XMLElement@price, 8<, 829.99<D<D,
XMLElement@book, 8category ® WEB<, 8XMLElement@title, 8lang ® en<, 8XQuery Kick Start<D,
XMLElement@author, 8<, 8James McGovern<D, XMLElement@author, 8<, 8Per Bothner<D,
XMLElement@author, 8<, 8Kurt Cagle<D, XMLElement@author, 8<, 8James Linn<D, XMLElement@author,
8<, 8Vaidyanathan Nagarajan<D, XMLElement@year, 8<, 82003<D, XMLElement@price, 8<, 849.99<D<D,
XMLElement@book, 8category ® WEB<, 8XMLElement@title, 8lang ® en<, 8Learning XML<D, XMLElement@
author, 8<, 8Erik T. Ray<D, XMLElement@year, 8<, 82003<D, XMLElement@price, 8<, 839.95<D<D<D, 8<D

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 FunctionalProgramming-Egypt-2010.nb

In[128]:= ClearAll@doc, where, orderBy, e, att, attribute, data, returnD;


doc@XMLObject@DocumentD@_, root_, _DD := root;
where = Select;
orderBy = Sort;
e@n_StringD := es Ì Cases@es, XMLElement@n , _, _D, ¥D;
att@XMLElement@_ , rules_, _D, n_StringD := Hn . Hrules ~ Join ~ 8_ ® Φ<LL;
attribute@XMLElement@_ , rules_, _D, n_StringD := 8n ® Hn . rulesL<;
attribute@ n_StringD := es Ì attribute@ð, nD & ž es;
attribute@ n_String, pred_D := el Ì pred@att@el, nDD;
data@n_StringD := es Ì Cases@es, XMLElement@n , _, 8d_<D ® d, ¥D;
data@n_String, pred_D := es Ì HCases@es, XMLElement@n , _, 8d_<D ; pred@dD, ¥D != 8<L;
return@es_, f_D := f ž es;

Mathematica XQuery DSL in Action

XPath Expressions

All book titles

In[140]:= doc@xmlD  e@"book"D  data@"title"D

Out[140]= 8Everyday Italian, Harry Potter, XQuery Kick Start, Learning XML<

All book authors

In[141]:= doc@xmlD  e@"book"D  data@"author"D

Out[141]= 8Giada 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]:= Hdoc@xmlD  e@"book"DL ~


return ~ Hbs Ì
HHdata@"author"D@ðD . 8a_< ® aL ® Hdata@"title"D@ðD . 8t_< ® tLL & ž bs
L

Out[142]= 8Giada De Laurentiis ® Everyday Italian, J K. Rowling ® Harry Potter,


8James 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]:= Hdoc@xmlD  e@"book"DL ~


where ~ Hb Ì b  data@"price", ToExpression@ðD > 30 &DL ~
return ~ data@"title"D

Out[143]= 8XQuery Kick Start, Learning XML<

All titles in the COOKING category


FunctionalProgramming-Egypt-2010.nb 31

In[144]:= Hdoc@xmlD  e@"book"DL ~


where ~ Hb Ì b  attribute@"category", ð == "COOKING" &DL ~
return ~ data@"title"D

Out[144]= 8Everyday Italian<

All titles in the WEB category with price > 40

In[145]:= Hdoc@xmlD  e@"book"DL ~


where ~ Hb Ì H
Hb  data@"price", ToExpression@ðD > 40 &DL && Hb  attribute@"category", ð == "WEB" &DL
L L~
return ~ data@"title"D

Out[145]= 8XQuery Kick Start<

The order by function

Order by title in descending order

In[146]:= Hdoc@xmlD  e@"book"DL ~


where ~ Hb Ì b  attribute@"category", ð == "WEB" &DL ~
orderBy ~ HOrder@ð1  data@"title"D, ð2  data@"title"DD < 0 &L ~
return ~ data@"title"D

Out[146]= 8XQuery Kick Start, Learning XML<

All books in WEB category, ordered by title in ascending order, formatted as { title ® price } list

In[147]:= Hdoc@xmlD  e@"book"DL ~


where ~ Hb Ì b  attribute@"category", ð == "WEB" &DL ~
orderBy ~ HOrder@ð1  data@"title"D, ð2  data@"title"DD > 0 &L ~
return ~ Hbs Ì
HHdata@"title"D@ðD . 8t_< ® tL ® Hdata@"price"D@ðD . 8p_< ® pLL & ž bs
L

Out[147]= 8Learning XML ® 39.95, XQuery Kick Start ® 49.99<

¢ | £
32 FunctionalProgramming-Egypt-2010.nb

Example: SQL

Establish a Database Connection

In[148]:= H* HSQL memory db *L


Needs@"DatabaseLink`"D
bookstore = OpenSQLConnection@D;

Create the Book table

In[150]:= SQLDropTable@bookstore, ðD & ž SQLTableNames@bookstoreD;


SQLCreateTable@bookstore, SQLTable@"BOOK"D, 8
SQLColumn@"ID", "DataTypeName" ® "INTEGER"D,
SQLColumn@"TITLE", "DataTypeName" ® "VARCHAR", "DataLength" ® 128D,
SQLColumn@"YEAR", "DataTypeName" ® "VARCHAR", "DataLength" ® 4D,
SQLColumn@"PRICE", "DataTypeName" ® "FLOAT"D
<D;
SQLTableNames@bookstoreD

Out[152]= 8BOOK<

Load books from XML

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

< & ž bsL

Out[154]= 88Everyday Italian, 2005, 30.00<, 8Harry Potter, 2005, 29.99<,


8XQuery Kick Start, 2003, 49.99<, 8Learning XML, 2003, 39.95<<

Load books into the Database

In[155]:= MapIndexed@
SQLInsert@bookstore, "BOOK", 8"ID", "TITLE", "YEAR", "PRICE"<, ð2 ~ Join ~ ð1D &, booksD;

Query the Database

In[156]:= SQLSelect@bookstore, "BOOK"D  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


FunctionalProgramming-Egypt-2010.nb 33

Close the Database Connection

In[157]:= CloseSQLConnection@bookstoreD

¢ | £
34 FunctionalProgramming-Egypt-2010.nb

Example: Geometric Transformation

The RotationTransform Function


Understanding the Function

In[158]:= RotationTransform@ΘD

Cos@ΘD -Sin@ΘD 0
Out[158]= TransformationFunctionA Sin@ΘD Cos@ΘD 0 E
0 0 1

In[159]:= RotationTransform@ΘD ž 8x, y<

Out[159]= 8x Cos@ΘD - y Sin@ΘD, y Cos@ΘD + x Sin@ΘD<

Creating a Replacement Rule

In[160]:= RotationTransform@ΘD ž 8x, y< . 8a_, b_< ® 8x ® a, y ® b<

Out[160]= 8x ® x Cos@ΘD - y Sin@ΘD, y ® y Cos@ΘD + x Sin@ΘD<

Testing Our Rule

In[161]:= Iy == x2 M . 8x ® x Cos@ΘD - y Sin@ΘD, y ® y Cos@ΘD + x Sin@ΘD<

2
Out[161]= y Cos@ΘD + x Sin@ΘD Š Hx Cos@ΘD - y Sin@ΘDL

In[162]:= Iy Cos@ΘD + x Sin@ΘD Š Hx Cos@ΘD - y Sin@ΘDL2 M . Θ ® 90 °

2
Out[162]= x Š y
FunctionalProgramming-Egypt-2010.nb 35

In[163]:= ContourPlotA9y Š x2 , x Š y2 =, 8x, -2 Π, 2 Π<, 8y, -2 Π, 2 Π<,


Axes ® True, Frame ® False, ContourStyle ® 88Thick, Red<, 8Thick, Blue<<E

Out[163]=
-6 -4 -2 2 4 6

-2

-4

-6

Creating a Simple Rotate Function

In[164]:= rotate@eq_, Θ_D := Heq . HRotationTransform@ΘD ž 8x, y< . 8a_, b_< ® 8x ® a, y ® b<LL

In[165]:= 9rotateAy == x2 , 90 °E, rotate@y == Sin@xD, 30 °D=  FullSimplify

1
2
Out[165]= 9x Š y , x + 3 y Š 2 SinA J 3 x - yNE=
2
36 FunctionalProgramming-Egypt-2010.nb

The Rotate Function in Action

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

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, vrfD;

Vertex = VertexT@d$ : _D;


vertex@d_D := VertexT@dD;
value@VertexD := d$;

Graph = GraphT@rep$ : 88_VertexT, 8_VertexT ...<< ...<D;


graph@rep : 88_VertexT, 8_VertexT ...<< ...<D := GraphT@repD;
graph@rep : 88_VertexT ® 8_VertexT ...<< ...<D :=
GraphT@Hð . 88x_ ® y : 8__<< ¦ 8x, y<<L & ž repD;
rep@GraphD := rep$;

Leaf = LeafT@v$ : VertexD;


leaf@v : VertexD := LeafT@vD;
vertex@LeafD := v$;

Branch = BranchT@v$ : Vertex, tail$ : 8__<D;


branch@v : Vertex, 8<D := leaf@vD;
branch@v : Vertex, l : 8___<D := BranchT@v, lD;
vertex@BranchD := v$;
tail@BranchD := tail$;

succ@g : Graph, v : VertexD := Cases@rep ž g, 8u : Vertex, adj_< ; u == v ® adjD  Flatten;

dft@g : Graph, v : VertexD := branch@v, dft@g, ðD & ž succ@g, vDD;

concatMap@f_, l : 8__<D := Fold@Join, 8<, 8Flatten ž f ž ð< & ž lD;

chains@g : GraphD := chains@dft@g, Hrep ž gL@@1DD@@1DDDD;


chains@l : LeafD := 88vertex ž l<<;
chains@b : BranchD := HconcatMap@8vertex ž b, ð< &, chains@ðDDL & ž tail ž b  Flatten@ð, 1D &;

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

In[219]:= LayeredGraphPlot@g  toRules, VertexRenderingFunction ® vrfD  Magnify@ð, 1D &  Dynamic

Out[219]= Α Β Γ

Α1 Α2 Α3 Β1 Β2 Β3 Γ1 Γ2 Γ3

Chains and Chains Plot

In[196]:= chains@gD  Dynamic

Out[196]= 88VertexT@ΜD, VertexT@ΑD, VertexT@Α1 D<,


8VertexT@ΜD, VertexT@ΑD, VertexT@Α2 D<, 8VertexT@ΜD, VertexT@ΑD, VertexT@Α3 D<,
8VertexT@ΜD, VertexT@ΒD, VertexT@Β1 D<, 8VertexT@ΜD, VertexT@ΒD, VertexT@Β2 D<,
8VertexT@ΜD, VertexT@ΒD, VertexT@Β3 D<, 8VertexT@ΜD, VertexT@ΓD, VertexT@Γ1 D<,
8VertexT@ΜD, VertexT@ΓD, VertexT@Γ2 D<, 8VertexT@ΜD, VertexT@ΓD, VertexT@Γ3 D<<

In[220]:= 8GraphPlot@ð, VertexRenderingFunction ®


vrfD  Magnify@ð, 1D &< & ž toRules ž chains ž g  Partition@ð, 3D &  TableForm  Dynamic

Μ Α Α1 Μ Α Α2

Out[220]= Μ Β Β1 Μ Β Β2

Μ Γ Γ1 Μ Γ Γ2

¢ | £
FunctionalProgramming-Egypt-2010.nb 39

Example: Sound

The Sound of Mathematics

In[198]:= n11 = 811, 2, 7, 9, 11, 2, 7, 5, 11, 2, 7, 4, 2, 2, 2<;


a11 = n11 ;
a12 = ð + 12 & ž n11 ;
a13 = a12 ~ Join ~ a11 ;
a14 = a13 ~ Join ~ Reverse@a12 D ~ Join ~ n11 ;
s1 = Sound@SoundNote@ð, .1, "Flute"D & ž Ha14 LD;
n21 = 82, 3, 7, 2, 3, 7, 2, 3, 9, 9, 7, 3<;
a21 = n21 ;
a22 = Hð + 12 & ž n21 L . 8xs__< ® 8xs, xs<;
a23 = a22 ~ Join ~ a21 ~ Join ~ Reverse@Hð + 12 & ž a21 LD ~ Join ~ Reverse@a21 D;
s2 = Sound@SoundNote@ð, .1, "Piano"D & ž Ha23 LD;
EmitSound@8s1 , s2 <D

¢ | £

You might also like