Haskell—List comprehensions

part1.

Prelude> [2^n | n <- [1..10]]
[2,4,8,16,32,64,128,256,512,1024]
Prelude> [2^n | n <- [1..10],2^n >= 10, 2^n < 100]
[16,32,64]
  • 2^n: the expression for the elements of the resulting list
  • n <- [1…10]: tells where the variable values come from
  • 2^n >= 10, 2^n < 100: can be predicates or filters placing additional constraints on which value to use.

part2.

Prelude> [x | x <- "outrageous",not(elem x "aeiou")]
"trgs"
Prelude> [x | x <- "outrageous",not(x `elem` `aeiou`)]
"trgs"
Prelude> [[x|x <- word, not(x `elem` "aeiou")]| word <- ["bell","book","candle"]]
["bll","bk","cndl"]
  • First two snippets have the same function that remove vowels, elem[^1] is a Haskell function.
  • Third snippets is a nesting list comprehension, inner list comprehension [x|x <- word, not(xelem"aeiou")]remove all of the vowels from the word, and outer list comprehension does that for each word in the list.
  • we use backtick[^2] in the last twosnippet to make infix.

[^1]elem:

Function:elem
Type:Eq a => a -> [a] -> Bool
Descriptions:returns True if the list contains an item equal to the first argument

Example:

Prelude> 14 `elem` [1..10]
False
Prelude> elem 1 [1..10]
True
Prelude> 'o' `elem` "tom"
True

[^2]backtick:

Prelude>10.0 / 5.0
2.0
Prelude> div 10 5
2
Prelude> 10 `div` 5
2

Divison can be written in 3 different ways, as the above show.
we might want to write it as an infix notation as if it were an operator and then we can do that with the backtick, so i can put div operator in backticks and then it becomes an operator


part3.

Here is another example:

Prelude> [[x*y | x <-[1..5]] | y <- [1..5]]
[[1,2,3,4,5],[2,4,6,8,10],[3,6,9,12,15],[4,8,12,16,20],[5,10,15,20,25]]

The inner list comprehension[x*y | x <-[1..5]] multiplies by the each possible value of y.
The outer list comprehension [[x*y | x <-[1..5]] | y <- [1..5]] does that for each possible value of x.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值