Haskell --- List Comprehension List集合操作

版权声明:学习交流为主,未经博主同意禁止转载,禁止用于商用。 https://blog.csdn.net/u012965373/article/details/82938482
// 生成x在区间内的2倍值
ghci> [x*2 | x <- [1..10]]  
[2,4,6,8,10,12,14,16,18,20]

// 生成x在区间内的2倍值,并且大雨12的数
[x * 2 | x <- [1..10], x * 2 >= 12]
  
// 生成50到100之间,对7做除法余数是3的数 
ghci> [ x | x <- [50..100], x `mod` 7 == 3]  
[52,59,66,73,80,87,94]  

// 函数若x是10,"BOOM",否则 "BANG"
boomBangs xs = [ if x 10 then "BOOM!" else "BANG!" | x <- xs, odd x]  

// 测试上面的函数
ghci> boomBangs [7..13]  
["BOOM!","BOOM!","BANG!","BANG!"]  

// 函数在10与20之间,并且不等于13,15,19】
ghci> [ x | x <- [10..20], x /= 13, x /= 15, x /= 19]  
[10,11,12,14,16,17,18,20] 

// 分属于list1 与list2中的值的积
ghci> [ x*y | x <- [2,5,10], y <- [8,10,11]]  
[16,20,22,40,50,55,80,100,110]  

// 分属于list1 与list2中的值的乘积,并且乘积大于50的值
[x*y | x<-[2,5,10], y <- [8, 10, 11], x * y > 50]

// 分属于list1与list2的字符串拼接
ghci> let nouns = ["hobo","frog","pope"]  
ghci> let adjectives = ["lazy","grouchy","scheming"]  
ghci> [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns]  
["lazy hobo","lazy frog","lazy pope","grouchy hobo","grouchy frog", "grouchy pope","scheming hobo",
"scheming frog","scheming pope"] 

// 生成一个求长度的函数 
length' xs = sum [1 | _ <- xs]  

// 去除非大写的字符
removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]  

// 上面函数的测试
ghci> removeNonUppercase "Hahaha! Ahahaha!"  
"HA"  
ghci> removeNonUppercase "IdontLIKEFROGS"  
"ILIKEFROGS"  

// 在不循环,不拆开list的情况下,去除所有的奇数
ghci> let xxs = [[1,3,5,2,3,1,2,4,5],[1,2,3,4,5,6,7,8,9],[1,2,4,2,1,6,3,1,3,2,3,6]]  
ghci> [ [ x | x <- xs, even x ] | xs <- xxs]  
[[2,2,4],[2,4,6,8],[2,4,2,6,2,6]] 


猜你喜欢

转载自blog.csdn.net/u012965373/article/details/82938482