haskell 1 basic and list If Expression List Range List Comprehension (Filtering) Tuple

Taking Notes from http://learnyouahaskell.com

  • infix (sanwich) : + - * /
  • prefix
1
2
x = x + x
doubleUs x y = doubleMe x + doubleMe y

If Expression

1
doubleSmallNumber x = if x > 100 then x else x * 2

List

“Hello” 只是 [‘h’,’e’,’l’,’l’,’o’] 的语法糖而已

Operators ++ : !! > >=

  • ++ 会有遍历左边的List

    1
    2
    > [1, 2, 3, 4] ++ [9, 10, 11, 12]
    [1,2,3,4,9,10,11,12]
  • : List 前端插入元素
    [1,2,3] == 1:2:3:[]

  • !! 按照索引取得 List 中的元素, 0-based index

    1
    2
    > "Steven" !! 1
    t
  • Compare Array > >=

    1
    2
    [3,2,1] > [2,1,0]
    True

Method

head tail last init length null reverse take drop minimum maximum sum product elem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
ghci> head [5,4,3,2,1]
5
ghci> tail [5,4,3,2,1]
[4,3,2,1]
ghci> last [5,4,3,2,1]
1
ghci> init [5,4,3,2,1]
[5,4,3,2]
ghci> length [5,4,3,2,1]
5
ghci> null [1,2,3]
False
ghci> reverse [5,4,3,2,1]
[1,2,3,4,5]
ghci> take 3 [5,4,3,2,1]
[5,4,3]
ghci> take 5 [1,2]
[1,2]
ghci> drop 3 [8,4,2,1,5,6]
[1,5,6]
ghci> minimum [8,4,2,1,5,6]
1
ghci> maximum [1,9,2,3,4]
9
ghci> sum [5,2,1,6,3,2,5,7]
31
ghci> product [6,2,1,2]
24
ghci> 4 `elem` [3,4,5,6]
True

Range

1
2
3
4
5
ghci> [1..20]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
ghci> ['a'..'z']
"abcdefghijklmnopqrstuvwxyz"
ghci> [20,19..1]
  • cycle
  • repeat
  • replicate
1
2
3
4
5
6
7
ghci> take 24 [13,26..]
ghci> take 10 (cycle [1,2,3])
[1,2,3,1,2,3,1,2,3,1]
ghci> take 10 (repeat 5)
[5,5,5,5,5,5,5,5,5,5]
ghci> replicate 3 10
[10,10,10]

List Comprehension (Filtering)

1
2
ghci> [x*2 | x <- [1..10], x*2 >= 12]
[12,14,16,18,20]
1
2
3
boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]
ghci> boomBangs [7..13]
["BOOM!","BOOM!","BANG!","BANG!"]
1
length' xs = sum [1 | _ <- xs]

Tuple

1
2
3
4
5
6
7
8
9
10
ghci> fst (8,11)
8
ghci> fst ("Wow", False)
"Wow"
ghci> snd (8,11)
11
ghci> zip [1,2,3,4,5] [5,5,5,5,5]
[(1,5),(2,5),(3,5),(4,5),(5,5)]
ghci> zip [1 .. 5] ["one", "two", "three", "four", "five"]
[(1,"one"),(2,"two"),(3,"three"),(4,"four"),(5,"five")]
1
2
3
ghci> let rightTriangles = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c == 24]
ghci> rightTriangles
[(6,8,10)]