Haskell趣学指南-学习笔记(3)

本文介绍了Haskell中的Range、等差数列生成、comprehension概念,展示了如何使用这些工具创建函数并处理列表操作,如循环、取值、重复和条件判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值