haskell-复习

list 一些操作


Prelude> head [1,2,3,4]
1
Prelude> tail [1,2,3,4]
[2,3,4]
Prelude> init [1,2,3,4]
[1,2,3]
Prelude> last [1,2,3,4]
4
Prelude> take 2 [1,2,3,4]
[1,2]
Prelude> length [1,2,3,4]
4
Prelude> max
max       maxBound  maximum
Prelude> maximum [1,2,3,4]
4
Prelude> minimum  [1,2,3,4]
1
Prelude> null [1,2,3,4]
False
Prelude> reverse [1,2,3,4]
[4,3,2,1]

根据索引取值 !!
Prelude> [1,2,3,4]!!2
3
Prelude> [1,2,3,4]!!1
2
Prelude> [1,2,3,4]!!0

在列表前插入值
Prelude> 1:[1,2,3,4]
[1,1,2,3,4]

生成指定数组

Prelude> [1,2..20]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Prelude> [1,4..20]
[1,4,7,10,13,16,19]

列表推导
Prelude> [ x | x <- [50..100], x `mod` 7 == 3]
[52,59,66,73,80,87,94]

ghci> [x*2 | x <- [1..10], x*2 >= 12]
[12,14,16,18,20]

类型系统

基本类型 Int, Intager, Double, Float

检测基本类型


Prelude> :t True
True :: Bool
Prelude> :t 1
1 :: Num a => a
Prelude> :t 1.2
1.2 :: Fractional a => a
Prelude> :t (1,2)
(1,2) :: (Num t, Num t1) => (t, t1)
Prelude> :t Char

检测函数的类型


Prelude> :t fst
fst :: (a, b) -> a
Prelude> :t tail
tail :: [a] -> [a]
Prelude> :t head
head :: [a] -> a
Prelude> :t init
init :: [a] -> [a]

注意不能在ghci中声明函数的类型,这个原因暂时没搞懂。

ord Ord 包含可比较大小的型别。除了函数以外,我们目前所谈到的所有型别都属于 Ord 类。Ord 包中包含了<, >, <=, >= 之类用于比较大小的函数。compare 函数取两个 Ord 类中的相同型别的值作参数,回传比较的结果。这个结果是如下三种型别之一:GT, LT, EQ。


ghci> "Abrakadabra" < "Zebra"  
True  
ghci> "Abrakadabra" `compare` "Zebra"  
LT  
ghci> 5 >= 2  
True  
ghci> 5 `compare` 3  
GT

参考

ready-go type-and-typeclass

Loading Disqus comments...
Table of Contents