28
List Comprehension Yan Huang

List Comprehension - Indiana University Bloomington

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: List Comprehension - Indiana University Bloomington

ListComprehensionYanHuang

Page 2: List Comprehension - Indiana University Bloomington

SetComprehensionsInmathematics,thecomprehension notationcanbeusedtoconstructnewsetsfromoldsets.

{x2 | x Î {1...5}}

Theset{1,4,9,16,25}ofallnumbersx2 suchthatxisanelementoftheset{1…5}.

Page 3: List Comprehension - Indiana University Bloomington

ListsComprehensionsInHaskell,asimilarcomprehensionnotationcanbeusedtoconstructnewlists fromoldlists.

[x^2 | x ¬ [1..5]]

Thelist[1,4,9,16,25]ofallnumbersx^2 suchthatxisanelementofthelist[1..5].

Page 4: List Comprehension - Indiana University Bloomington

z Theexpressionx¬ [1..5]iscalledagenerator,asitstateshowtogeneratevaluesforx.

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

Page 5: List Comprehension - Indiana University Bloomington

z Changingtheorder ofthegeneratorschangestheorderoftheelementsinthefinallist:

> [(x,y) | y ¬ [4,5], x ¬ [1,2,3]]

[(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)]

z Multiplegeneratorsarelikenestedloops,withlatergeneratorsasmoredeeplynestedloopswhosevariableschangevaluemorefrequently.

Page 6: List Comprehension - Indiana University Bloomington

> [(x,y) | y ¬ [4,5], x ¬ [1,2,3]]

[(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)]

For example:

x ¬ [1,2,3] is the last generator, so the value of the x component of each

pair changes most frequently.

Page 7: List Comprehension - Indiana University Bloomington

DependentGenerators

Latergeneratorscandepend onthevariablesthatareintroducedbyearliergenerators.

[(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.

Page 8: List Comprehension - Indiana University Bloomington

Usingadependentgeneratorwecandefinethelibraryfunctionthatconcatenates alistoflists:

Forexample:

> concat [[1,2,3],[4,5],[6]]

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

Page 9: List Comprehension - Indiana University Bloomington

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

Page 10: List Comprehension - Indiana University Bloomington

Guards

Listcomprehensionscanuseguards torestrictthevaluesproducedbyearliergenerators.

[x | x ¬ [1..10], even x]

Thelist[2,4,6,8,10]ofallnumbersxsuchthatxisanelementofthelist

[1..10]andxiseven.

Page 11: List Comprehension - Indiana University Bloomington

Usingaguardwecandefineafunctionthatmapsapositiveintegertoitslistoffactors:

Forexample:

> factors 15

[1,3,5,15]

Page 12: List Comprehension - Indiana University Bloomington

factors :: Int ® [Int]factors n =

[x | x ¬ [1..n], n `mod` x == 0]

Usingaguardwecandefineafunctionthatmapsapositiveintegertoitslistoffactors:

Forexample:

> factors 15

[1,3,5,15]

Page 13: List Comprehension - Indiana University Bloomington

Apositiveintegerisprime ifitsonlyfactorsare1anditself.Hence,usingfactorswecandefineafunctionthatdecidesifanumberisprime:

Forexample:

> prime 15False

> prime 7True

Page 14: List Comprehension - Indiana University Bloomington

Apositiveintegerisprime ifitsonlyfactorsare1anditself.Hence,usingfactorswecandefineafunctionthatdecidesifanumberisprime:

prime :: Int ® Boolprime n = factors n == [1,n]

Forexample:

> prime 15False

> prime 7True

Page 15: List Comprehension - Indiana University Bloomington

Usingaguardwecannowdefineafunctionthatreturnsthelistofallprimes uptoagivenlimit:

Forexample:

> primes 40

[2,3,5,7,11,13,17,19,23,29,31,37]

Page 16: List Comprehension - Indiana University Bloomington

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

Page 17: List Comprehension - Indiana University Bloomington

TheZipFunctionAusefullibraryfunctioniszip,whichmapstwoliststoalistofpairsoftheircorrespondingelements.

zip :: [a] ® [b] ® [(a,b)]

Forexample:

> zip [’a’,’b’,’c’] [1,2,3,4]

[(’a’,1),(’b’,2),(’c’,3)]

Page 18: List Comprehension - Indiana University Bloomington

Usingzipwecandefineafunctionreturnsthelistofallpairs ofadjacentelementsfromalist:

Forexample:

> pairs [1,2,3,4]

[(1,2),(2,3),(3,4)]

Page 19: List Comprehension - Indiana University Bloomington

Usingzipwecandefineafunctionreturnsthelistofallpairs ofadjacentelementsfromalist:

Forexample:

pairs :: [a] ® [(a,a)]pairs xs = zip xs (tail xs)

> pairs [1,2,3,4]

[(1,2),(2,3),(3,4)]

Page 20: List Comprehension - Indiana University Bloomington

Usingpairswecandefineafunctionthatdecidesiftheelementsinalistaresorted:

Forexample:

> sorted [1,2,3,4]True

> sorted [1,3,2,4]False

Page 21: List Comprehension - Indiana University Bloomington

Usingpairswecandefineafunctionthatdecidesiftheelementsinalistaresorted:

Forexample:

sorted :: Ord a Þ [a] ® Boolsorted xs =

and [x £ y | (x,y) ¬ pairs xs]

> sorted [1,2,3,4]True

> sorted [1,3,2,4]False

Page 22: List Comprehension - Indiana University Bloomington

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

Page 23: List Comprehension - Indiana University Bloomington

StringComprehensions

Astring isasequenceofcharactersenclosedindoublequotes.Internally,however,stringsarerepresentedaslistsofcharacters.

"abc" :: String

Means[’a’,’b’,’c’]::[Char].

Page 24: List Comprehension - Indiana University Bloomington

Becausestringsarejustspecialkindsoflists,anypolymorphic functionthatoperatesonlistscanalsobeappliedtostrings.Forexample:

> length "abcde"5

> take 3 "abcde""abc"

> zip "abc" [1,2,3,4]

[(’a’,1),(’b’,2),(’c’,3)]

Page 25: List Comprehension - Indiana University Bloomington

Similarly,listcomprehensionscanalsobeusedtodefinefunctionsonstrings,suchcountinghowmanytimesacharacteroccursinastring:

count :: Char ® String ® Intcount x xs =

length [x’ | x’ ¬ xs, x == x’]

Forexample:

> count ’s’ "Mississippi"4

Page 26: List Comprehension - Indiana University Bloomington

Exercises

Atriple(x,y,z)ofpositiveintegersiscalledpythagorean ifx2 +y2 =z2.Usingalistcomprehension,defineafunction

(1)

pyths :: Int ® [(Int,Int,Int)]

thatmapsanintegerntoallsuchtripleswithcomponentsin[1..n].Forexample:

> pyths 5[(3,4,5),(4,3,5)]

Page 27: List Comprehension - Indiana University Bloomington

Apositiveintegerisperfect ifitequalsthesumofallofitsfactors,excludingthenumberitself.Usingalistcomprehension,defineafunction

(2)

perfects :: Int ® [Int]

thatreturnsthelistofallperfectnumbersuptoagivenlimit.Forexample:

> perfects 500

[6,28,496]

Page 28: List Comprehension - Indiana University Bloomington

(xsi * ysi )åi = 0

n-1

Usingalistcomprehension,defineafunctionthatreturnsthescalarproductoftwolists.

Thescalarproduct oftwolistsofintegersxs andysoflengthnisgivebythesumoftheproductsofthecorrespondingintegers:

(3)