Haskell Study Note Lesson 5
Haskell Study Note Lesson 5
List
Creating Lists
Note : type homogeneous
[1,2,3][1..5]、[2,4..10]
Accessing List Elements
- index from 0
!!:list !! index
A safe way :
1 | safeIndex xs i = if i < lenght xs then Just(xs !! i) else Nothing |
Concatenation & Extension
- Concatenation :
++like[1, 2, 3] ++ [4, 5, 6] - Cons operator:
:like0 : [1, 2, 3]and we get[0, 1, 2, 3]
List Slicing
take:take 3 [1, 2, 3, 4, 5]is[1, 2, 3]drop:drop 2 [1, 2, 3, 4, 5]is[3, 4, 5]splitAt:splitAt 2 [1, 2, 3, 4, 5]is[1, 2], [3, 4, 5], which returns a tuple
A trick :
1 | let xs = [1..10] |
Basic Traversal
-
map1
2map (*2) [1, 2, 3, 4]
-- get [2, 4, 6, 8] -
fliter1
2filter even [1, 2, 3, 4, 5, 5]
-- get [2, 4, 6] -
head/tail1
2
3
4head [1, 2, 3]
-- 1
tail [1, 2, 3]
-- [2, 3]
Practice : Number List Tool
1 | numbers :: [Int] |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 zhangxixi的博客!
