1、Range,等步距填充(等差数列);
如:
ghci> [1..20]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
ghci> [2,4..20]
[2,4,6,8,10,12,14,16,18,20]
ghci> [3,6..20]
[3,6,9,12,15,18]
2、避免在
Range
中使用浮点数;
如:
ghci> [0.1, 0.3 .. 1]
[0.1,0.3,0.5,0.7,0.8999999999999999,1.0999999999999999]
3、comprehension概念,通过集合、条件范围等求值,如:
ghci> [x*2 | x <- [1..10], x*2 >= 12]
[12,14,16,18,20]
创建comprehension函数,如:
boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]
可以得到:
ghci> boomBangs [7..13]
["BOOM!","BOOM!","BANG!","BANG!"]
函数:
cycle,针对 cycle 无限循环的列表,可以采取 take ,只取前面几位,如:
ghci> take 10 (cycle [1,2,3])
[1,2,3,1,2,3,1,2,3,1]
ghci> take 12 (cycle "LOL ")
"LOL LOL LOL "
repeat ,同 cycle ,但是仅返回一个值,如:
ghci> take 10 (repeat 5)
[5,5,5,5,5,5,5,5,5,5]
replicate ,同 repeat ,但是写法简便,如:
ghci>replicate 3 10
[10,10,10]
mod,取余数,x 'mod' 7 == 3,如:
ghci> [ x | x <- [50..100], x `mod` 7 == 3]
[52,59,66,73,80,87,94]
odd,判断是否为奇数;even,判断是否为偶数,属于限制条件,如:
ghci> odd 8
False
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]]