1. 強類型
2. 靜態類型
3. 可自動推斷
額,我按照自己的理解解釋一下吧...
強類型不支持自動類型轉換,為了讓代碼可靠一些...
靜態類型是每個表達式或者變量的類型都是靜態不變的...
Haskell可以自動檢測表達式中常數的數據類型...
common basic types
char: Unicode字符
bool:True & False
Int : 在32位機器上是32位,在64位機器上是64位
Integer: 高精度整形
Double:64位浮點型
Function Application
一些函數需要注意的地方,就是如果你要把一個函數的值傳到另一個函數里,需要加一個括號以改變優先級
1 ghci>odd 3
2 True
3 ghci>even 6
4 True
5 ghci>compare (sqrt 2) 1
6 GT
7 ghci>compare (sqrt 2) 1 == GT
8 True
9 ghci>compare sqrt 2 1 == GT
10
11 <interactive>:16:1:
12 The function `compare' is applied to three arguments,
13 but its type `a0 -> a0 -> Ordering' has only two
14 In the first argument of `(==)', namely `compare sqrt 2 1'
15 In the expression: compare sqrt 2 1 == GT
16 In an equation for `it': it = compare sqrt 2 1 == GT
Composite Data Types: Lists and Tuples
字符串就是一個字符列表,head 函數可以返回列表的第一個元素,tail可以返回列表的除了第一個元素的所有元素。
1 ghci>head "figo"
2 'f'
3 ghci>tail "figo"
4 "igo"
5 ghci>tail [1,2,3]
6 [2,3]
還有另一種類型叫做“元組”。類似于C++的pair,連用法都極其相似。
ghci>snd (19910905,"hanfei")
"hanfei"
ghci>fst (19910905,"hanfei")
19910905
Function Types and Purity
:type 命令可以查看一個函數傳入的參數類型和返回的參數類型
Haskell的函數只允許調用傳入的參數,禁止使用全局變量。 這樣的函數叫做“純函數”。(略感坑爹)
1 ghci>:type lines
2 lines :: String -> [String]
3 ghci>lines "figo\nis\nstupid\nhahaha"
4 ["figo","is","stupid","hahaha"]
Haskell Soucre Files, and Writing Simple Functions
Haskell源文件的后綴是.hs,這樣的話vim就會有語法高亮了...
定義一個函數
1 -- add.hs by figo 05.16.2012
2 add a b = a + b
我們可以用:load add.hs來加載這個函數
1 ghci>:load add.hs
2 [1 of 1] Compiling Main ( add.hs, interpreted )
3 Ok, modules loaded: Main.
4 ghci>:type add
5 add :: Num a => a -> a -> a
6 ghci>add 1 2
7 3
Conditional Evaluation
利用if來寫一個drop函數:
1 -- myDrop.hs by figo 05.16.2012
2 myDrop n xs = if n <= 0 || null xs
3 then xs
4 else myDrop (n-1)(tail xs)
里面的類型都是自動檢測的... 額... 不用像C++那樣提前聲明
測試一下剛寫的東東
1 ghci>:load myDrop.hs
2 [1 of 1] Compiling Main ( myDrop.hs, interpreted )
3 Ok, modules loaded: Main.
4 ghci>myDrop 2 "figo"
5 "go"
6 ghci>myDrop 1 ["hanfei","figo","hello"]
7 ["figo","hello"]
Polymorphism in Haskell
Haskell的多態性指的是,如果一個函數可以把某參數當做任意類型處理。就像C++的template一樣。
ghci>:type fst
fst :: (a, b) -> a
Exercises
寫一個函數,功能是返回元素的倒數第二個值。
呃... 只能寫成這樣子了... 好渣... 求大神指點
1 -- lastButOne.hs by figo 05.16.2012
2 lastButOne xs = if(length (xs) <= 2)
3 then head xs
4 else lastButOne (tail xs)
5
posted on 2012-05-16 19:59
西月弦 閱讀(1634)
評論(3) 編輯 收藏 引用 所屬分類:
讀書筆記(Haskell)