haskell-logo.jpg
haskell_list.JPG
List 應(yīng)該翻譯成清單,我們程序員通常就叫 list 或者叫列表。list 無論對于計(jì)算機(jī)語言和程序都是很重要的,有一門語言就是叫 list 吧滴某。
let lostNumbers = [4,8,15,16,23,42]
print lostNumbers
如果我們將數(shù)組添加一個(gè)其他類型字符串呢,這樣做在 list 上是行不通的滋迈。需要元素類型保持一致霎奢。
main = do
let lostNumbers = [4,8,15,16,'o',42]
print lostNumbers
list的合并
在 haskell 中,連接符號為 ++饼灿。
main = do
let lostNumbers = [1,2,3,4] ++ [9,10,11,12]
print lostNumbers
在許多語言都將字符串認(rèn)為字符的集合幕侠,
main = do
let lostNumbers =['w','o'] ++ ['o','t']
print lostNumbers
為list添加元素
"A SMALL CAT"
[5,1,2,3,4,5]
我們可以嘗試 [] 添加到 [[]]
let createTwoDimensionArr = []:[[]]
print createTwoDimensionArr
上面是編譯不通過,不過如果向下面這樣碍彭,[[1,2]] 已經(jīng)有值編譯是可以通過的晤硕。
let createTwoDimensionArr = []:[[1,2]]
print createTwoDimensionArr
我可以通過添加操作符 : 來創(chuàng)建一個(gè)數(shù)組
```haskell
let createListWithSomething = 1:2:3:[]
print createListWithSomething
[[],[1,2]]
根據(jù)索引獲取數(shù)組的元素
let charAtSix = "zidea and matthew" !! 6
print charAtSix
'a'
這里推薦一版javascript 函數(shù)式編程,我是先看這本書庇忌,然后才開始學(xué)習(xí)haskell舞箍,這本書很好,但是翻譯不算好所以只好閱讀英文原版皆疹。書中長篇大論的概念也不是创译,所以理解起來對于我也有些困難。最近看了 ocaml 和 haskell 然后返回來再看感覺對 FP 有點(diǎn)感覺了墙基。當(dāng)時(shí)書中就介紹 tail head first last 等操作數(shù)組的方法软族,當(dāng)時(shí)感覺疑惑為什么要這樣做,看 haskell 后多少明白這樣做的原因和好處残制。
let lostNumbers = 5:[1,2,3,4,5]
let headOfList = head lostNumbers
print headOfList
let tailOfList = tail lostNumbers
print tailOfList
let lastOfList = last lostNumbers
print lastOfList
let initOfList = init lostNumbers
print initOfList
5
[1,2,3,4,5]
5
[5,1,2,3,4]
對于多維數(shù)組立砸,我們可以操作和操作一維數(shù)組類似
let twoDimensionList = [[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3]]
print twoDimensionList
let joinTwoDimesionList = [1,2,3]:twoDimensionList
print joinTwoDimesionList
[[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3]]
[[1,2,3],[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3]]
數(shù)組比較
在 haskell 中的數(shù)組比較,
let result = [6,3,2] > [3,2,1]
print result
λ [2,3,5]>[1,2,3]
True:: Bool
λ [0,3,5]>[1,2,3]
False:: Bool
λ [2,3,5]>[1,2,3]
True:: Bool
λ [2,3,5]>[1,6,3]
True:: Bool
λ [2,3,5]>[2,6,3]
False:: Bool
λ [2,3,5]>[1,6]
True:: Bool
λ [2,3,5]>[3,6]
False:: Bool
λ
數(shù)組長度
length [5,4,3,2,1]
λ null []
True:: Bool
λ null [1,2,3]
False:: Bool
take 和 drop 操作數(shù)組
通過 take 和 drop 從前或從后截取一定長度數(shù)組
λ take 1 [1,2,3]
[1]:: Num a => [a]
λ take 2 [1,2,3,,4,5]
<hint>:1:15: parse error on input ‘,’
λ take 2 [1,2,3,4,5]
[1,2]:: Num a => [a]
λ take 0 [1,2,3]
[]:: Num a => [a]
λ drop 3 [1,2,3,4,5,6]
[4,5,6]:: Num a => [a]
sum min max
這些符號就不做多解釋了初茶。
product 求乘積
λ product [1,2,3]
6:: Num a => a
elem 查看數(shù)組是否包含某個(gè)元素
λ 1 `elem` [2,3,4]
False:: Bool