صفحه 1:
isort :: [Int] -> [Int]
190۲6 ] [ 211
isort (head : tail) = insert head
(isort tail)
where insert v_ [] = [v]
insert v (h: t) =if v
<=h
thenv:h:t
else h : (insert
v t)
Main> isort [9,5,2,8,3]
Lecture 9 List
[2,3,5,8,9] Comprehension
صفحه 2:
List Comprehensions
Lecture 9 List
Comprehensions
صفحه 3:
quair list = [ x*x | x <- list ]
' generator (x is an element of list)
Main> squair [1,2,3,4,5]
[1,4,9,16,25]
General form
Body Selector
\ /
[ expression | qualifiers]
The selector is a list expression. It can be combined
with one or more guards, separated by commas. A
qualifier can be a generator or a filter(a boolean
expression restricting what is generated by the
generator.
Prelude>[x | >- ]1..10[ ی 4 = = 0] ۳
Comprehensions
دم رح
صفحه 4:
ample: Generating English Sentences
stat = [k++" "++y++" "+4+z++"."|
x <-["A","An","The"],
y <-["man","ape","dog"],
- ["runs","flies","ate"],
not(x == "An" && not(member (head
y) "“aeiou")|| R=" 48" Ge member
(head y) "“aeiou")]
["A man runs.","A man flies.","A man ate.","A dog
runs.","A dog flies.","A dog ate.","An ape runs.","An ape
flies.","An ape ate.","The man runs.","The man
flies.","The man ate." »"The ape,runs." ,"The ape
flies." ","The ape ate." ""Therdogssuns. "\"The dog
صفحه 5:
vgCouples :: [(Float,Float)] -> [Float]
avgCouple list = [ (at+b)/2 | (a,b) <- list ]
Prelude > avgCouples [(2.3, 3.7),(4.5, 5.5),(5.6, 8.4)]
[3.0,5.0,7.0]
Prelude> take 9 [(a,b,c)|a<-[1..],b<-[1..],c<-
[1..],at+b+c<1000]
[((1,1,1),(1,1,2),(1,1,3),(1,1,4),(1,1,5),(1,1,6),(1,1,7),
(1,1,8),(1,1,9)]
Prelude> [ (a,b) | a <- [1,2], b <- [3,4,5] ]
[(1,3),(1,4),(1,5),(2,3),(2,4),(2,5)]
Prelude > [(a,b)|a <- [1,2,3,4,5,6,7],b<-
[7,8,9,10,11,12],even a,odd b]
[(2,7),(2,9),(2,11),(4,7),(4,9),(4,11),(6,7),(6,9),(6,11)]
Prelude > [ (a,b) | a <- [2A srhe"], b <- 5
["dog","cat","bird"] ] Comprehensions
صفحه 6:
Function oddL
oddL []= []
oddL list = if even (head list)
then oddL (tail list)
else head list:oddL (tail list)
oddL []
oddL (h:t)
1
if evenh then oddL telse h:oddL t
Function oddL using list comprehension
OddL list = [x | x <- list, x ‘mod* 2 / = 0]
Lecture 9 List
Comprehensions
صفحه 7:
Quicksort
qsort [] = []
qsort (head:tail) = qsort [x | x <- tail, x < head]
++ [head]
++ qsort [x | x <- tail, x>=head]
Main> qsort [6,2,1,8,4,9]
[1,2,4,6,8,9]
Main> qsort ['c','b','a','s','d']
“abcds"
Main> qsort
["George","Paul","Andy","Martin","Abraham","Mary","Stewart"]
["Abraham","Andy","George","Martin","Mary","Paul","S
tewart"]
Main> qsort [[8,9,41,[1,3,51,[9,7,01,[6,9,2]]
111.3.5116.9.2118 9.4] [P=repepsions
7