functional programming in mathematica

39
Functional Programming in Mathematica An Introduction Hossam Karim ITWorx

Upload: hossam-karim

Post on 28-Nov-2014

6.782 views

Category:

Technology


2 download

DESCRIPTION

Functional Programming In Mathematica Talk, Egypt Mathematica Conference, 2010

TRANSCRIPT

Page 1: Functional Programming In Mathematica

Functional Programming in MathematicaAn Introduction

Hossam Karim

ITWorx

Page 2: Functional Programming In Mathematica

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 presentationsare samples not suitable for production, and are provided for the sole purpose of demonstration.

¢ | £

2 FunctionalProgramming-Egypt-2010.nb

Page 3: Functional Programming In Mathematica

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 y2= x4

- x2+ 1 can be defined as function by the triple notation

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

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

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

A more common notation is

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

Plotting a Function

Mathematica supports both function and curve plotting

FunctionalProgramming-Egypt-2010.nb 3

Page 4: Functional Programming In Mathematica

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

Out[1]=

-3 -2 -1 1 2 3x

-3

-2

-1

1

2

3y

4 FunctionalProgramming-Egypt-2010.nb

Page 5: Functional Programming In Mathematica

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

-3 -2 -1 1 2 3x

-3

-2

-1

1

2

3

y

Functional Programming Languages

Functional Programming Languages has always been the natural choice for implementing computer derived solutions for mathematicalproblems including Numerical Analysis, Combinatorics and Algorithms

Haskell

Implementation of the Quick Sort algorithm in Haskell. Demonstrates polymorphic types, pattern matching, list comprehension andimmutability

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 partialfunctions 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)) }}

FunctionalProgramming-Egypt-2010.nb 5

Page 6: Functional Programming In Mathematica

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<

¢ | £

6 FunctionalProgramming-Egypt-2010.nb

Page 7: Functional Programming In Mathematica

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

In[10]:= á

1

Sin@ΘD

â Θ

Out[10]= -2 EllipticFA1

2

Π

2- Θ , 2E

Accurate results

In[11]:= ¶Θ % �� FullSimplify

Out[11]=1

Sin@ΘD

Algorithms

Optimized algorithms

FunctionalProgramming-Egypt-2010.nb 7

Page 8: Functional Programming In Mathematica

In[12]:= Timing@Sort@RandomInteger@81, 10000000<, 100000DDD �� Short

Out[12]//Short=80.04, 89, 400, 418, 657, 719, 859, 947, 1057, 1061, �99982�,

9 998951, 9998953, 9999009, 9999077, 9999123, 9999227, 9999236, 9999314, 9999497<<

Algorithm analysis

In[13]:= T@nD �. RSolveA9T@nD � TA2 n

3E + 1, T@1D � 1=, T@nD, nE

Out[13]= 91 +Log@nD

LogA3

2E

=

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

¢ | £

8 FunctionalProgramming-Egypt-2010.nb

Page 9: Functional Programming In Mathematica

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

FunctionalProgramming-Egypt-2010.nb 9

Page 10: Functional Programming In Mathematica

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

10 FunctionalProgramming-Egypt-2010.nb

Page 11: Functional Programming In Mathematica

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

Out[223]=

¢ | £

FunctionalProgramming-Egypt-2010.nb 11

Page 12: Functional Programming In Mathematica

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]:= [email protected], square@2D, square@2 + 3 äD, square@xD, square@SomeDataType@xDD<

Out[28]= 94, 4, 4, x2, x2=

Patterns and Lists

Expressive patterns on lists, notice how ordering is important

One or more __̈2

Zero or more ___©

3

In[29]:= ClearAll@listOpD;listOp@8<D := 8<listOp@8x_, y_<D := 8y, x< H* flip a tuple *LlistOp@8x_, xs__<D := 8xs< H* drop the first element *LlistOp@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<<<

¢ | £

12 FunctionalProgramming-Egypt-2010.nb

Page 13: Functional Programming In Mathematica

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

¢ | £

FunctionalProgramming-Egypt-2010.nb 13

Page 14: Functional Programming In Mathematica

Pure Functions

Defining a Pure Function

The Ì Notation

A function that squares its argument

In[41]:= x Ì x2

Out[41]= FunctionAx, x2E

Square function applied at 3

In[42]:= Ix Ì x2M@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

14 FunctionalProgramming-Egypt-2010.nb

Page 15: Functional Programming In Mathematica

Higher-Order Functions

Map

Map as a function call

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

Out[46]= 9a2, b2, c2, d2=

Using the ( /@ ) Notation

In[47]:= Ix Ì x2M �� 8a, b, c, d<

Out[47]= 9a2, b2, c2, d2=

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<

Out[48]= 99Μ, Σ2,ã

-Hx-ΜL2

2 Σ2

2 Π Σ

=, 922

Π

Σ,H-8 + 3 ΠL Σ2

Π

,

ã-

x2

2 Σ22

Πx2

Σ3=, 9Α Β, Α Β2,

ã-x

Β x-1+Α Β-Α

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 &

Out[215]=

O

C

O

C

N

C

N

C

N

C

NC

N

C

N

C

N

C

N

C

N

C

NC

N

C

C

C

C

C

C H

CH C

H

C H

CH

C

H

CH

C

H

CH

C

H

O

C

O

C

N

C

N

C

N

C

NC

N

C

N

C

N

C

N

C

N

C

NC

N

C

C

C

C

C

C H

CH C

H

C H

CH

C

H

CH

C

H

CH

C

H

O

O NNN

NNNNNN

NN

O

O NNN

NNNNNN

NN

Or used inside a manipulation

FunctionalProgramming-Egypt-2010.nb 15

Page 16: Functional Programming In Mathematica

Or used inside a manipulation

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

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

Manipulate@Map@

ImageCompose@tux, ImageResize@ð, Scaled@scaleDD, 8horizontal, vertical<D &, browsersD �� GraphicsRow,

8scale, 0.5, 1<,8horizontal, 60, 200, 10<,8vertical, 60, 200, 10<

D

Out[52]=

scale

horizontal

vertical

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

16 FunctionalProgramming-Egypt-2010.nb

Page 17: Functional Programming In Mathematica

In[218]:= Manipulate@8Fold@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

Out[218]=

step

F

F

F

F

x a

b

c

d

Fold Left

F

d F

c F

b F

a x

Fold Right

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

Out[57]=

88<<88<, 8Α<<

88<, 8Α<, 8Β<, 8Α, Β<<

88<, 8Α<, 8Β<, 8Γ<, 8Α, Β<, 8Α, Γ<, 8Β, Γ<, 8Α, Β, Γ<<

NestWhileList

In[58]:= NestWhileListAx Ìx

2, 32, i Ì i ¹ 1E

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

Pascal Triangle

Pascal triangle can be defined using binomials

FunctionalProgramming-Egypt-2010.nb 17

Page 18: Functional Programming In Mathematica

In[59]:= Table@Binomial@n, kD, 8n, 0, 4<, 8k, 0, n<D �� Column@ð, CenterD &

Out[59]=

81<

81, 1<

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<Dpascal@h_D := NestWhileList@81< ~Join~tuples@ðD ~Join~ 81< &, 81<, Length@ðD < h &Dpascal@9D �� Column@ð, CenterD &

Out[63]=

81<

81, 1<

81, 2, 1<

81, 3, 3, 1<

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;

hexagon@x_, y_D := PolygonATableA9SinA2 Π k

6E + x, CosA

2 Π k

6E + y=, 8k, 6<EE

render@l_ListD := GraphicsA9HueALength@lD

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

Out[67]=

h

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

3 n + 1 Problem

18 FunctionalProgramming-Egypt-2010.nb

Page 19: Functional Programming In Mathematica

3 n + 1 Problem

In[68]:= collatz := n Ì ∂ n�2 EvenQ@nD

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

x

970,35,106,53,160,

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

¢ | £

FunctionalProgramming-Egypt-2010.nb 19

Page 20: Functional Programming In Mathematica

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 ainsert n Empty = Node Empty n Emptyinsert 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 abst [] = Emptybst (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 := nilbst@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, thebinary 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

20 FunctionalProgramming-Egypt-2010.nb

Page 21: Functional Programming In Mathematica

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

Out[89]=1

0 2

3

4

6

5 7

8

10

9 12

11 13

88,3,10,1,0,4,6,5,9,12,2,7,13,11<

We can then visualize a random BST construction step by step

FunctionalProgramming-Egypt-2010.nb 21

Page 22: Functional Programming In Mathematica

In[214]:= With@8l = RandomInteger@81, 100<, 10D �� DeleteDuplicates<,Manipulate@8Text@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<DD

Out[214]=

step

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

43

11 50

48

57

91

99

92

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

¢ | £

22 FunctionalProgramming-Egypt-2010.nb

Page 23: Functional Programming In Mathematica

Pattern Matching and Transformation

Matching Cases

Match Cases

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

Out[91]= 9a2=

Match Cases with a predicate

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

Out[92]= 9a2, c4, e6=

Match Cases with a predicate and a transformation rule

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

Out[93]= 9b4, d6=

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

FunctionalProgramming-Egypt-2010.nb 23

Page 24: Functional Programming In Mathematica

In[96]:= ClearAll@gD;g = 8

Μ ® Α, Μ ® Β,Α ® i, Α ® j ,Β ® a, Β ® b<;

GraphPlot@g, VertexLabeling ® True, AspectRatio ® 0.2D �� Magnify@ð, 1.5D &

Out[98]= ΜΑ Β

i

j a

b

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 �� FromDigitsLNestWhileList@alg196, 77, ð < 10000000 &D

Out[101]= 877, 154, 605, 1111, 2222, 4444, 8888, 17776, 85547, 160105, 661166, 1322332, 3654563, 7 309126, 13528163<

Recursively test if a sequence is a palindrome

In[102]:= isPalindrome@seq_ListD := seq �. 88< 8x_< ¦ True,8x_, xs___, y_< ¦ x == y && isPalindrome@8xs<D<

Test the sequence

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

Out[103]= 877, 1111, 2222, 4444, 8888, 661166, 3654563<

Example: Run Length Encoding

Perform run length encoding on a finite sequence

By Frank Zizza, 1990

Use replace repeated (//.)

24 FunctionalProgramming-Egypt-2010.nb

Page 25: Functional Programming In Mathematica

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

¢ | £

FunctionalProgramming-Egypt-2010.nb 25

Page 26: Functional Programming In Mathematica

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, thehierarchy 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 := rid@XMLElement@_, as_, 8___<DD := "id" �. ascost@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

26 FunctionalProgramming-Egypt-2010.nb

Page 27: Functional Programming In Mathematica

In[232]:= rec@root@xmlDD �� GraphPlot@ð, VertexLabeling ® True, EdgeLabeling ® TrueD & �� Magnify@ð, 1D &

Out[232]=

0

0

0

1

2

3

4

5

6

7

8

9

root

a

b

c

a1

a2

a3

b1

b2

b3

c1

c2

c3

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 := rsequenceList@XMLElement@"sequenceML", _, seqs_DD := sequence �� seqssequence@e : XMLElement@"sequence", 8"seqID" ® id_<, cs_DD :=

8seqID ® 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<

FunctionalProgramming-Egypt-2010.nb 27

Page 28: Functional Programming In Mathematica

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<

¢ | £

28 FunctionalProgramming-Egypt-2010.nb

Page 29: Functional Programming In Mathematica

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/bookwhere $x/price>30order by $x/titlereturn $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

FunctionalProgramming-Egypt-2010.nb 29

Page 30: Functional Programming In Mathematica

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

30 FunctionalProgramming-Egypt-2010.nb

Page 31: Functional Programming In Mathematica

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 Ì HHb �� data@"price", ToExpression@ðD > 40 &DL && Hb �� attribute@"category", ð == "WEB" &DLL 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<

¢ | £

FunctionalProgramming-Egypt-2010.nb 31

Page 32: Functional Programming In Mathematica

Example: SQL

Establish a Database Connection

In[148]:= H* HSQL memory db *LNeeds@"DatabaseLink`"Dbookstore = OpenSQLConnection@D;

Create the Book table

In[150]:= SQLDropTable@bookstore, ðD & �� SQLTableNames@bookstoreD;SQLCreateTable@bookstore, SQLTable@"BOOK"D, 8SQLColumn@"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 Ì8data@"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

32 FunctionalProgramming-Egypt-2010.nb

Page 33: Functional Programming In Mathematica

Close the Database Connection

In[157]:= CloseSQLConnection@bookstoreD

¢ | £

FunctionalProgramming-Egypt-2010.nb 33

Page 34: Functional Programming In Mathematica

Example: Geometric Transformation

The RotationTransform Function

Understanding the Function

In[158]:= RotationTransform@ΘD

Out[158]= TransformationFunctionA

Cos@ΘD -Sin@ΘD 0

Sin@ΘD Cos@ΘD 0

0 0 1

E

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 == x2M �. 8x ® x Cos@ΘD - y Sin@ΘD, y ® y Cos@ΘD + x Sin@ΘD<

Out[161]= y Cos@ΘD + x Sin@ΘD � Hx Cos@ΘD - y Sin@ΘDL2

In[162]:= Iy Cos@ΘD + x Sin@ΘD � Hx Cos@ΘD - y Sin@ΘDL2M �. Θ ® 90 °

Out[162]= x � y2

34 FunctionalProgramming-Egypt-2010.nb

Page 35: Functional Programming In Mathematica

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

-6

-4

-2

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

Out[165]= 9x � y2, x + 3 y � 2 SinA1

2J 3 x - yNE=

FunctionalProgramming-Egypt-2010.nb 35

Page 36: Functional Programming In Mathematica

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

ContourStyle ® [email protected], HueAð1

ΠE=

E & �� Range@0, 360, 10D

E �� Magnify@ð, 1D &

Out[233]=

¢ | £

36 FunctionalProgramming-Egypt-2010.nb

Page 37: Functional Programming In Mathematica

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;

FunctionalProgramming-Egypt-2010.nb 37

Page 38: Functional Programming In Mathematica

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@Α1D<,8VertexT@ΜD, VertexT@ΑD, VertexT@Α2D<, 8VertexT@ΜD, VertexT@ΑD, VertexT@Α3D<,8VertexT@ΜD, VertexT@ΒD, VertexT@Β1D<, 8VertexT@ΜD, VertexT@ΒD, VertexT@Β2D<,8VertexT@ΜD, VertexT@ΒD, VertexT@Β3D<, 8VertexT@ΜD, VertexT@ΓD, VertexT@Γ1D<,8VertexT@ΜD, VertexT@ΓD, VertexT@Γ2D<, 8VertexT@ΜD, VertexT@ΓD, VertexT@Γ3D<<

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

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

Out[220]=

Μ Α Α1 Μ Α Α2

Μ Β Β1 Μ Β Β2

Μ Γ Γ1 Μ Γ Γ2

¢ | £

38 FunctionalProgramming-Egypt-2010.nb

Page 39: Functional Programming In Mathematica

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@a12D ~Join~n11;s1 = Sound@SoundNote@ð, .1, "Flute"D & �� Ha14LD;n21 = 82, 3, 7, 2, 3, 7, 2, 3, 9, 9, 7, 3<;a21 = n21;a22 = Hð + 12 & �� n21L �. 8xs__< ® 8xs, xs<;a23 = a22 ~Join~a21 ~Join~Reverse@Hð + 12 & �� a21LD ~Join~Reverse@a21D;s2 = Sound@SoundNote@ð, .1, "Piano"D & �� Ha23LD;EmitSound@8s1, s2<D

¢ | £

FunctionalProgramming-Egypt-2010.nb 39