php/Math   
Recreational Mathematics   
   home  |  library  |  contact
 Math Notes
 Math Programming [25]
 Regression [3]
 Data Mining [17]
 Notation [6]
 Linear Algebra [9]
 Stats & Prob [15]
 Math Cognition [5]
 Space & Physics [6]
 Formulas [5]
 Fun & Games [2]
 Haskell [1]
 Bayes Theory [1]
 Site News [0]
 Math Projects [5]
 Polynomials [1]
 Calculus [9]
 Number Theory [3]
 Optimization [2]
 Financial [1]

 Math Links
 PHP/ir
 Andrew Gelman
 Chance Wiki
 Daniel Lemire
 KD Knuggets
 Social Stats
 MySQL Performance
 Hunch.net
 Matthew Hurst
 JMLR
 JSS
 Hal Daume III
 Math Notes >> Haskell

The power of list comprehension [Haskell
Posted on January 28, 2007 @ 10:47:43 PM by Paul Meagher

One often sees the following set builder notation in mathematics:

{ x2 | x in S }

The bar | means "such that" so this expression defines a set that consists of squared x values such that x is in S (where S is itself a set which is left undefined in this example).

The functional programming language Haskell has perhaps the cleanest and most powerful sytax for emulating this set builder notation.

[ x^2 | x <- [1..5] ] 

Hitting return on this list comprehension expression yields:

[1, 4, 9, 16, 25]

The general recipe for list comprehension is [ expression | generator ] where you can have optional additional generators and filters after the bar |. With list comprehension we can do some impressive one liners such as:

[ x | x <- [1..12], y <- [1..12], 12 == x*y ]

Which returns all the factors of 12:

[1, 2, 3, 4, 6, 12]

We can also develop powerful little programs such as this one by O'Donnell, Hall and Page which makes a mailing label for every employee under 30 who is making at least $15000 a year:

db = [("Ann Smith", "29 Byres Road", 30, 48000),
      ("Alan Jones", "36 High Street", 25, 170000),
       ... 
     ]

[name ++ "/n" ++ addr ++ "/n" | (name, addr, age, sal) <- db, age < 30, sal >= 15000 ]

Cool!

Permalink 

 Archive 
 


php/Math Project
© 2011. All rights reserved.