Download List Comprehension

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Abuse of notation wikipedia , lookup

Large numbers wikipedia , lookup

Big O notation wikipedia , lookup

Non-standard calculus wikipedia , lookup

List of prime numbers wikipedia , lookup

Dirac delta function wikipedia , lookup

Vincent's theorem wikipedia , lookup

Addition wikipedia , lookup

History of the function concept wikipedia , lookup

Function (mathematics) wikipedia , lookup

Proofs of Fermat's little theorem wikipedia , lookup

Elementary mathematics wikipedia , lookup

Transcript
ListComprehension
YanHuang
SetComprehensions
Inmathematics,thecomprehension notationcanbe
usedtoconstructnewsetsfromoldsets.
{x2 | x Î {1...5}}
Theset{1,4,9,16,25}ofallnumbersx2 suchthatx
isanelementoftheset{1…5}.
ListsComprehensions
InHaskell,asimilarcomprehensionnotationcanbe
usedtoconstructnewlists fromoldlists.
[x^2 | x ¬ [1..5]]
Thelist[1,4,9,16,25]ofallnumbersx^2 suchthat
xisanelementofthelist[1..5].
z Theexpressionx¬ [1..5]iscalledagenerator,asit
stateshowtogeneratevaluesforx.
z Comprehensionscanhavemultiple generators,
separatedbycommas.Forexample:
> [(x,y) | x ¬ [1,2,3], y ¬ [4,5]]
[(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]
z Changingtheorder ofthegeneratorschangesthe
orderoftheelementsinthefinallist:
> [(x,y) | y ¬ [4,5], x ¬ [1,2,3]]
[(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)]
z Multiplegeneratorsarelikenestedloops,withlater
generatorsasmoredeeplynestedloopswhose
variableschangevaluemorefrequently.
For example:
> [(x,y) | y ¬ [4,5], x ¬ [1,2,3]]
[(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)]
x ¬ [1,2,3] is the last generator, so
the value of the x component of each
pair changes most frequently.
DependentGenerators
Latergeneratorscandepend onthevariablesthatare
introducedbyearliergenerators.
[(x,y) | x ¬ [1..3], y ¬ [x..3]]
Thelist[(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)]
ofallpairsofnumbers(x,y)suchthatx,y are
elementsofthelist[1..3]andy³ x.
Usingadependentgeneratorwecandefinethelibrary
functionthatconcatenates alistoflists:
Forexample:
> concat [[1,2,3],[4,5],[6]]
[1,2,3,4,5,6]
Usingadependentgeneratorwecandefinethelibrary
functionthatconcatenates alistoflists:
concat :: [[a]] ® [a]
concat xss = [x | xs ¬ xss, x ¬ xs]
Forexample:
> concat [[1,2,3],[4,5],[6]]
[1,2,3,4,5,6]
Guards
Listcomprehensionscanuseguards torestrictthe
valuesproducedbyearliergenerators.
[x | x ¬ [1..10], even x]
Thelist[2,4,6,8,10]ofallnumbersx
suchthatxisanelementofthelist
[1..10]andxiseven.
Usingaguardwecandefineafunctionthatmapsa
positiveintegertoitslistoffactors:
Forexample:
> factors 15
[1,3,5,15]
Usingaguardwecandefineafunctionthatmapsa
positiveintegertoitslistoffactors:
factors :: Int ® [Int]
factors n =
[x | x ¬ [1..n], n `mod` x == 0]
Forexample:
> factors 15
[1,3,5,15]
Apositiveintegerisprime ifitsonlyfactorsare1and
itself.Hence,usingfactorswecandefineafunction
thatdecidesifanumberisprime:
Forexample:
> prime 15
False
> prime 7
True
Apositiveintegerisprime ifitsonlyfactorsare1and
itself.Hence,usingfactorswecandefineafunction
thatdecidesifanumberisprime:
prime :: Int ® Bool
prime n = factors n == [1,n]
Forexample:
> prime 15
False
> prime 7
True
Usingaguardwecannowdefineafunctionthat
returnsthelistofallprimes uptoagivenlimit:
Forexample:
> primes 40
[2,3,5,7,11,13,17,19,23,29,31,37]
Usingaguardwecannowdefineafunctionthat
returnsthelistofallprimes uptoagivenlimit:
primes :: Int ® [Int]
primes n = [x | x ¬ [2..n], prime x]
Forexample:
> primes 40
[2,3,5,7,11,13,17,19,23,29,31,37]
TheZipFunction
Ausefullibraryfunctioniszip,whichmapstwoliststoa
listofpairsoftheircorrespondingelements.
zip :: [a] ® [b] ® [(a,b)]
Forexample:
> zip [’a’,’b’,’c’] [1,2,3,4]
[(’a’,1),(’b’,2),(’c’,3)]
Usingzipwecandefineafunctionreturnsthelistofall
pairs ofadjacentelementsfromalist:
Forexample:
> pairs [1,2,3,4]
[(1,2),(2,3),(3,4)]
Usingzipwecandefineafunctionreturnsthelistofall
pairs ofadjacentelementsfromalist:
pairs :: [a] ® [(a,a)]
pairs xs = zip xs (tail xs)
Forexample:
> pairs [1,2,3,4]
[(1,2),(2,3),(3,4)]
Usingpairswecandefineafunctionthatdecidesifthe
elementsinalistaresorted:
Forexample:
> sorted [1,2,3,4]
True
> sorted [1,3,2,4]
False
Usingpairswecandefineafunctionthatdecidesifthe
elementsinalistaresorted:
sorted :: Ord a Þ [a] ® Bool
sorted xs =
and [x £ y | (x,y) ¬ pairs xs]
Forexample:
> sorted [1,2,3,4]
True
> sorted [1,3,2,4]
False
Usingzipwecandefineafunctionthatreturnsthelist
ofallpositions ofavalueinalist:
positions :: Eq a Þ a ® [a] ® [Int]
positions x xs =
[i | (x’,i) ¬ zip xs [0..], x == x’]
Forexample:
> positions 0 [1,0,0,1,0,1,1,0]
[1,2,4,7]
StringComprehensions
Astring isasequenceofcharactersenclosedindouble
quotes.Internally,however,stringsarerepresentedas
listsofcharacters.
"abc" :: String
Means[’a’,’b’,’c’]::[Char].
Becausestringsarejustspecialkindsoflists,any
polymorphic functionthatoperatesonlistscanalso
beappliedtostrings.Forexample:
> length "abcde"
5
> take 3 "abcde"
"abc"
> zip "abc" [1,2,3,4]
[(’a’,1),(’b’,2),(’c’,3)]
Similarly,listcomprehensionscanalsobeusedto
definefunctionsonstrings,suchcountinghowmany
timesacharacteroccursinastring:
count
:: Char ® String ® Int
count x xs =
length [x’ | x’ ¬ xs, x == x’]
Forexample:
> count ’s’ "Mississippi"
4
Exercises
(1) Atriple(x,y,z)ofpositiveintegersiscalled
pythagorean ifx2 +y2 =z2.Usingalist
comprehension,defineafunction
pyths :: Int ® [(Int,Int,Int)]
thatmapsanintegerntoallsuchtripleswith
componentsin[1..n].Forexample:
> pyths 5
[(3,4,5),(4,3,5)]
(2) Apositiveintegerisperfect ifitequalsthesumofall
ofitsfactors,excludingthenumberitself.Usinga
listcomprehension,defineafunction
perfects :: Int ® [Int]
thatreturnsthelistofallperfectnumbersuptoa
givenlimit.Forexample:
> perfects 500
[6,28,496]
(3) Thescalarproduct oftwolistsofintegersxs andys
oflengthnisgivebythesumoftheproductsofthe
correspondingintegers:
n-1
å (xs * ys )
i
i
i=0
Usingalistcomprehension,defineafunctionthat
returnsthescalarproductoftwolists.